Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@rmpel
Last active December 18, 2019 13:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmpel/af4e95269c9250d42dd8afbd912d7692 to your computer and use it in GitHub Desktop.
Save rmpel/af4e95269c9250d42dd8afbd912d7692 to your computer and use it in GitHub Desktop.
Redirect to browser language in WordPress + WPML when the default language is in a subfolder (as the rest) and there is no real homepage.
<?php
// redirect to language if no language
add_action( 'after_setup_theme', function () {
if ( is_admin() ) {
// we are on admin; do nothing
return;
}
if ( $GLOBALS['pagenow'] === 'wp-login.php' ) {
// We're on the login page, do nothing
return;
}
// ignore POST request as redirecting them would do more harm than good.
if ( $_SERVER['REQUEST_METHOD'] === 'POST' ) {
// we are processing a POST; do nothing
return;
}
// we cannot use the wpml_active_language filter here because -- like any other
// API of WPML -- it defaults to the default language, which we are trying to avoid.
global $wpml_request_handler;
$req_lang = $wpml_request_handler->get_requested_lang();
if ( $req_lang ) {
// the page requested has a language; do nothing
return;
}
// what should we use as fallback language?
$default_language = apply_filters( 'wpml_default_language', null );
if ( ! $default_language ) {
$default_language = 'en';
}
// what language is the user's browser set-up? If the user does not pass a language, use the default.
if ( ! isset( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) || ! $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) {
$_SERVER['HTTP_ACCEPT_LANGUAGE'] = $default_language;
}
// what languages are configured?
$allowed_languages = apply_filters( 'wpml_active_languages', array() );
$allowed_languages = array_keys( $allowed_languages );
// test the configured language codes against the requested language
preg_match( '/^(' . implode( '|', $allowed_languages ) . ')/', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $match );
// if there is no match, defer to the default language.
if ( ! $match || ! $match[1] ) {
$match = array( '', $default_language );
}
// prepare the redirect; inject the language code.
// dev note: $_SERVER['REQUEST_URI'] includes GET-parameters
$redirect = '/' . $match[1] . '/' . ltrim( $_SERVER['REQUEST_URI'], '/' );
// redirect the user
wp_redirect( $redirect, 307 );
// bye bye.
exit;
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment