Answer the question
In order to leave comments, you need to log in
How to take current user in WP loop in plugin?
I'm trying to make a WordPress plugin that would change the language depending on the language of the current user set in the profile.
The code itself works fine if you put it in fucntion.php, but if you make a plugin out of it, it doesn't work.
The bottom line is that the code changes the language through "switch_to_locale()", while changing the language to the language of the user who is currently logged in, is taken through "get_user_locale()" after checking "is_user_logged_in()".
But if we push this code into the plugin, then we get that when the code works, the user has not yet been defined (googled), but if we hang the user definition on the event after the initialization of WordPress (init), then "switch_to_locale ()" will not work.
The code itself (if very abbreviated)
function current_user_locale_language() {
if (is_user_logged_in()) {
$logged_in_user_locale = get_user_locale();
if ( in_array( $logged_in_user_locale, array( 'en_US', 'en_AU', 'en_CA', 'en_GB' ) ) ) {
$user_locale = 'en_US';
} elseif ( in_array( $logged_in_user_locale, array( 'ru_RU', 'ru_UA' ) ) ) {
$user_locale = 'ru_RU';
} else {
$user_locale = get_locale();
}
} else {
$user_locale = get_locale();
}
return $user_locale;
}
switch_to_locale(current_user_locale_language());
Answer the question
In order to leave comments, you need to log in
Haven't tried your code. If the problem is in the order of the call, then you can use cookies as an option.
in switch_to_locale
we specify what is stored in cookies, if there is nothing, then the default value or not call at all switch_to_locale
. current_user_locale_language()
hang on init
time it works there. We add a check to see if there is a value in cookies, if there is, then we do nothing, if not, then we execute the script code and instead return $user_locale
save the received value in cookies and reload the page.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question