Set language per post

I couldn’t find an answer so I ended up providing the solution.

It wasn’t simple given that I am not an expert with wordpress nor with php but WordPress documentation is great so here is the solution:

// Set the post language when loading up the page based on the store meta
function ppl_set_post_language() {
    $postID = url_to_postid( $_SERVER["REQUEST_URI"] );
    if ($postID > 0) {
        $postLanguage = esc_attr( get_post_meta( $postID, '_ppl_post_language', true ) );
        if ( ! empty( $postLanguage ) ) {
            global $locale;
            $locale = $postLanguage;
        }
    }
}
// Any call to 'url_to_postid' earlier then 'setup_theme' will generate a fatal error.
add_action('setup_theme', 'ppl_set_post_language');

When editing the post or page, store the language code (e.g. en_US or ar) in the post meta. This part is easy, however, the problem is when displaying the page when do you run the code that check the langauage? If you run it too early you won’t have the post ID since it is not yet loaded by wordpress, and if you wait and run the code late it will be too late since wordpress will load the default language. The sweet spot I found is at action setup_theme since at that step the translations are not loaded yet and we can call url_to_postid to get the post ID which we use to retrieve the post meta.

After doing this I thought why not create a WordPress plugin that others can benefit from and here it is:

https://wordpress.org/plugins/per-post-language/

Leave a Comment