Changing the language of a single page

I have a wordpress site in a language that aligns RTL, but some pages are in English. These pages look terrible, however, because the English text is aligned with the RTL language, and punctuation, etc. appear on the wrong the side.

How can I set the language for a single page or several individual pages?

Topic language translation multi-language Wordpress

Category Web


I needed something similar for translation & direction purposes.

By defining $direction for each post, 'ltr' or 'rtl'...using this simple plugin ... I edited the plugin by adding following action to plugin.php file:

add_action('wp', function($locale){
    // get post meta from database, which is generated by the plugin
    global $post;
    $direction = get_post_meta($post->ID, 'os_custom_box_for_rtl', true);
    // set locale language based on post meta
    $locale = ($direction == 'rtl')? 'ar':'en_US'; // ...or use your own locale codes
    // if not admin area, do switch! it will work for frontend only per specific page/post
    is_admin() or switch_to_locale( $locale );
});

Here is a fix for the problem of timing in the solution by @jack-johansson:

add_action('wp', function() {
  if ( is_page('slug-here') ) {
    add_filter('locale', function( $locale ) {
      return 'en_US';
    });
  }
});

You should use locale hook to solve your task.

Important note that you can't add it in theme and use is_page function, because it will define later.

So you have to create plugin or must use plugin with url parsing this way:

add_filter('locale', function($locale) {
    $path = trim($_SERVER['REQUEST_URI'], "/");

    // get last part as slug
    $arr = explode("/", $path);
    $slug = end($arr);

    if($slug === 'MY_SLUG')
      return 'ru_RU';

    return $locale;
});

Related answer: Change locale at runtime?


The locale filter that allows you to set the locale specifically. You can check the current page, and alter the value based on that.

add_filter('locale', 'change_my_locale');
function change_my_locale( $locale ) {
    if ( is_page('slug-here') ) {
        return 'en_US';
    }
    return $locale;
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.