Detect current language of a post with PHP & JS (using Polylang)...

If you are writing a wordpress multi language site like me, you can end up with Polylang, one of the best free wordpress translation plugin. You can show a language switch button on your web, but to tell your reader there is a translation of a particular post available, you must know how to detect current language of a post.

detect current language of a post in php and js

After hours of searching how to detect current language of a post with Polylang, I found this post. The post is old, but the code still works. It helps you detect if a particular post has translation then show the language switch button automatically at the top/bottom of the post.

How to detect current language of a post with Polylang in PHP?

The original code works well with newest wordpress version, but it not allows you to put the language switch button where you want. Moreover, the button sometimes shows twices when there is a youtube embed code in the post. After days of studying PHP & JS, I has improved the code.

Now with the new code, you will be able to:

1 – Show the language switch button anywhere you want.
2 – Detect current language of a post in both PHP and Javascript.
3 – Allow you to put a quick translation directly in the template, no need to register the text in functions.php

Build a function that helps you detect current language of a post then show the language switch botton

Just put these code in your functions.php in the theme folder. This will check if a post has a translation available, then show the language switch button. You can easily customize your button as you like in the $newContent part.


function fususu_lang_available(){
    $newContent = '';   
    global $polylang;
    $translationIds = PLL()->model->post->get_translations(get_the_ID());
    $currentLang = pll_get_post(get_the_ID(), pll_current_language());
    
    foreach ($translationIds as $key=>$translationID){
        if($translationID != $currentLang){
            $availableLang = $polylang->model->get_languages_list();
            foreach( $availableLang as $lang){
                if($key == $lang->slug){
                    $name_other_lang = get_the_title($translationID);
                    $newContent.= '<a class="read-other-lang" href="' . get_permalink($translationID) . '"><i class="fa fa-external-link"></i> ';
                      if ( $lang->slug == 'vi'){
                      $newContent.= 'Vietnamese Version <img src="' . $lang-/>flag_url . '" alt="' . $lang->name . '"> '.$name_other_lang;
                        } else {
                            $newContent.= 'English Version <img src="' . $lang-/>flag_url . '" alt="' . $lang->name . '" > '.$name_other_lang;
                        }
                    $newContent.= '</a>';
                }
            }
        }
    }
    return $newContent;
}
add_shortcode('langavail', 'fususu_lang_available');

Now you can show the language switch button everywhere you want. If you are in the post, you can call it by a shortcode like [langavail]. Or you can call it automatically in a post, by put this code in the template.


<?php echo fususu_lang_available(); ?>

The button will also shows the title of the post in other language. It’s easy, right?

How to detect current language of a post for other purposes?

In some cases, you might want to show a particular content to specific users in other countries. For example, on my homepage I show a random quote for my visitors. If visitors are from Vietnam, the content will be in Vietnamese. If they are from other countries, content will be in English.

To do that, you need to detect current language of the page they are in. First, put this simple code in your functions.php


function vn() {
   if ( function_exists( 'pll_current_language' ) ) {
    $lang = pll_current_language('slug');
   }
   if ($lang == "vn") {
      return true;
   } else {
      return false;
   }
}


Note: This code will detect current language of a post or page is Vietnamese or not, then return the value true or false for you to use later. To make it work, you must change vn to the slug of your target language (it’s defined when you create the language with Polylang plugin)

For example, if you want to check if current language of a post or page is French, you can use this code.


function fr() {
   if ( function_exists( 'pll_current_language' ) ) {
    $lang = pll_current_language('slug');
   }
   if ($lang == "fr") {
      return true;
   } else {
      return false;
   }
}


Now it’s time to use our functions. In a template, you can use this code below.


  <?php if(vn()) { ?>   
      // show something for Vietnamese user here 
  <?php } else { ?>
      // show something if they are not Vietnamese
  <?php } ?>

How to detect current language of a post with JS?

In another secenario, you might want some javascripts to work only if users using a specific languague. How to do that? There are two ways.

First method, you can also use the PHP functions above. Just put javascript codes in the if statement like this code below. It will show a message box to your users.


  <?php if(vn()) { ?>   
      <script>
         alert('You are Vietnamese?');
      </script>
  <?php } else { ?>
      // alert('You are not Vietnamese?');
  <?php } ?>

Second method is a tricky one. To use this, you must put a language switch button that Polylang provides you somewhere in your website. For example, I put this code at my footer.php


<?php pll_the_languages( array( 'show_flags' => 1,'show_names' => 1, 'hide_current' => 1 ) ); ?>

I notice that Polylang will put a lang-item class along with the language switch button. So I use javascript to get the locale of the current language, like this:


  <script>
    function en() {
      var lang = jQuery('.lang-item a')[0].getAttribute('lang');
      if (lang === 'en-US') { return true;} else { return false;}
    } 
</script>

That js code will let you know if user language is English or not. Now I can use it along with other js for specific users.


  <script>
    if(en()) { 
        alert('Are you English?');
    } else {
       alert('You are not English, am I right?');
    }
</script>

Now you know how to detect current language of a post in both PHP and JS!

Just apply for your website and let me know if it works well or not. See you in next wordpress tips!





See you with good news!

FuSuSu wrote 10/10/2019. Updated 10/10/2019. In Wordpress Tips & Codes.

P.s. To motivate me, you can just google this keyword detect current language of a post, find my blog there then comment the position. Thank you so much!

Thank for your visit, I have a gift for you…

Leave a Reply

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

TREASURE CHEST

!!!



You can wait for to get the hidden content, or just share to see it now. Sharing is the key to succeed!

UNLOCK NOW!