Use Each User's Profile Language as Their Polylang Language
Makes Polylang pick the language set in a logged-in user's profile when it decides which language to show them on the homepage, instead of relying on browser settings.
Opens WPIDE on
Code
add_filter( 'pll_preferred_language', function ( $slug ) {
if ( ! is_user_logged_in() || ! function_exists( 'pll_languages_list' ) ) {
return $slug;
}
$user_locale = get_user_meta( get_current_user_id(), 'locale', true );
if ( ! $user_locale ) {
return $slug;
}
$locales = pll_languages_list( array( 'fields' => 'locale' ) );
$slugs = pll_languages_list( array( 'fields' => 'slug' ) );
$index = array_search( $user_locale, $locales, true );
return false !== $index && isset( $slugs[ $index ] ) ? $slugs[ $index ] : $slug;
} );
Notes
Only applies when the profile language is one of your Polylang languages; otherwise Polylang's normal detection runs.
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.