Here is the complete and a better solution to only change theme (front-end) or plugin language. It even works for changing even a specific page/post etc. language as well.
TLDR; There is a filter called locale
, which determines which language to load. You can change to your specific language based on the conditions that you prefer.
Changing only Theme language, or based on other conditions, without touching the admin dashboard language.
add_filter('locale', function($locale) {
if( is_admin() ) {
return $locale; // Leave default language if it is admin side.
}
// You can load language based on any conditional tags here, like, is_page(), is_singular(), is_archive() etc.
// I want to change the language for all front end in this particular example.
$locale = 'en_US'; // Change to your required language. The language must be installed and loaded.
return $locale; // Return language to be used.
});
Before you change the language, you may need to load that language first.
In your theme or child theme, load the custom language by using this snippet.
add_action( 'after_setup_theme', function() {
// Assuming your language files are in /wp-content/themes/your-theme/languages
// Don't forget to change 'text-domain' to your theme text-domain.
// For Theme.
load_theme_textdomain( 'text-domain', get_template_directory() . '/languages' );
// For Child Theme
load_child_theme_textdomain( 'text-domain', get_stylesheet_directory() . '/languages' );
// Remove the load_child_theme_textdomain if you are using it for the main theme,
// OR Remove load_theme_textdomain if you are loading child theme language.
});
Similarly, you can change language based on URL, or for your plugin page, etc.
Hope it'll help. OR let me know if I missed something.