Automatic language tagging with Polylang in WordPress

World of flagsI use the Polylang plugin for the multi-language capabilities of the sites written on WordPress. One feature that I implemented and find extremely useful is the automatic tagging of the posts with a language tag (like “en”, “ru”, etc.) when the post is saved. The code that goes into the functions.php file of the theme is as follows:

function tigra_add_polylang_language_tag( $post_id ) {
        global $polylang;
        if (isset($polylang) ) {
                if ( !$polylang->model->get_post_language($post_id) ) {
                        $polylang->model->set_post_language($post_id, pll_default_language());
                }
                $post_lang = $polylang->model->get_post_language($post_id);
                $languages = $polylang->model->get_languages_list(array('fields' => 'slug'));
                $post_tags = get_the_tags($post_id);
                $post_tags = wp_list_pluck($post_tags, 'name');
                $post_tags = array_diff($post_tags, $languages);
                if ( empty($post_tags) ) {
                        $post_tags = array();
                }
                array_push($post_tags, $post_lang->slug);
                wp_set_post_tags($post_id, $post_tags);
        }
}
add_action( 'save_post', 'tigra_add_polylang_language_tag' );

The code verifies that the default language is set (as I heard some reports that the mobile applications sometimes manage to bypass the Polylang capabilities) and sets it if necessary. Then, it extracts all tags from the post, wipes all supported (selected in Polylang configuration) language tags and adds a single tag corresponding to the language of the post.

This procedure makes sure that the language tag is always present and that the old tag is wiped when you change the language of the post. Now you can retrieve the posts, sort or do other manipulations based on the tag.

Big kudos to Chouby for the plugin and the help with code.

One thought on “Automatic language tagging with Polylang in WordPress

  1. Thank you so much for this snippet! Can’t wait to test it!

Leave a Reply

Your email address will not be published. Required fields are marked *