WPML | Custom languages selector

August 28th, 2018

For a project, i need to develop a custom wpml languages selector:

For selector with languages flags only, add this directly in function.php of you theme.

function language_selector_flags(){
    $languages = icl_get_languages('skip_missing=0&orderby=code');
    if(!empty($languages)){
        foreach($languages as $l){
            if(!$l['active']) echo '<a href="'.$l['url'].'">';
            echo '<img src="'.$l['country_flag_url'].'" height="12" alt="'.$l['language_code'].'" width="18" />';
            if(!$l['active']) echo '</a>';
        }
    }
}

and this in your theme template where you want the selector appears :

<div id="flags_language_selector"><?php language_selector_flags(); ?></div >

For Selector with languages code only, add this directly in you function.php

function language_selector_flags(){
    $languages = icl_get_languages('skip_missing=0&orderby=code');
    if(!empty($languages)){
        foreach($languages as $l){
            if(!$l['active']) echo '<a href="'.$l['url'].'">';
            echo '<span>'.$l['language_code'].'</span>';
            if(!$l['active']) echo '</a>';
        }
    }
}

and this in your theme template where you want the selector appears :

<div id="flags_language_selector"><?php language_selector_flags(); ?></div >

For selector with select box with language code. add this directly in you function.php

function language_selector_flags(){
  $languages = icl_get_languages('skip_missing=0&orderby=code');
  if(!empty($languages)){
    echo '<select onchange="if (this.value) window.location.href=this.value">';
      foreach($languages as $l){
          if($l['active']) echo '<option value="'.$l['url'].'" selected >'.$l['language_code'].'</option>';
          else echo '<option value="'.$l['url'].'">'.$l['language_code'].'</option>';
      }
      echo '</select>';
  }
}

and this in your theme template where you want the selector appears :

<div id="flags_language_selector"><?php language_selector_flags(); ?></div >