Redirect First-Time Visitors to Their Language Section
Sends visitors who land on the homepage to the matching language section (such as /fr/ or /de/) based on their browser language, once; their choice is then remembered.
Opens WPIDE on
Code
$wpide_sections = array( // Browser language => homepage path, e.g. 'fr' => '/fr/', 'de' => '/de/'.
);
add_action( 'template_redirect', function () use ( $wpide_sections ) {
if ( ! $wpide_sections || ! is_front_page() || is_user_logged_in() || isset( $_COOKIE['wpide_lang_seen'] ) || empty( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) ) {
return;
}
$agent = isset( $_SERVER['HTTP_USER_AGENT'] ) ? strtolower( sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) ) : '';
if ( '' === $agent || preg_match( '/bot|crawl|spider|slurp|preview|lighthouse/', $agent ) ) {
return;
}
setcookie( 'wpide_lang_seen', '1', time() + YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true );
$header = strtolower( sanitize_text_field( wp_unslash( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) ) );
$first = substr( $header, 0, 2 );
if ( isset( $wpide_sections[ $first ] ) ) {
nocache_headers();
wp_safe_redirect( home_url( $wpide_sections[ $first ] ), 302 );
exit;
}
} );
Notes
Map language codes to the paths of your translated homepages. Search engine bots are never redirected, so every version stays indexable.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.