Creating a child theme PHP language redirect
-
I would like to have a WordPress site re-direct visitors to either an English (/en) or French (/fr) sub-folder of a multisite installation that’s using sub-folders. I’m new to WordPress and first thought I could use an .htaccess redirect but have since learned that with WordPress it’s better to do this using a functions.php file placed in each child theme folder. Someone was kind enough to suggest the following code, but it’s not working. I’m wondering if anyone here knows why?
The functions.php file inside the English (/en) child theme:
<?php function language_redirect() { if ( !is_user_logged_in() && !is_admin() ) { $user_lang = substr( $_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2 ); if ( $user_lang == 'fr' ) { wp_redirect( home_url( '/fr/' ) ); exit(); } } } add_action( 'template_redirect', 'language_redirect' );
functions.php file inside the French (/fr) child theme:
<?php function language_redirect() { if ( !is_user_logged_in() && !is_admin() ) { $user_lang = substr( $_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2 ); if ( $user_lang == 'en' ) { wp_redirect( home_url( '/en/' ) ); exit(); } } } add_action( 'template_redirect', 'language_redirect' );
( Thank you to narolainfotech (@narolainfotech) )
I suspect the problem might be that the wp_redirect appends the home_url with either “/en/” or “/fr/”. But as the two home_url’s are already example.com/en and example.com/fr this code results in “example.com/en/fr/“, “example.com/fr/en/“, example.com/en/en/, etc .. which don’t exist.
Is there a way to fix this? Or is this code correct and the problem is elsewhere (like between my keyboard and my chair <g>) ….?
- The topic ‘Creating a child theme PHP language redirect’ is closed to new replies.