WPML shortcode for language flags Print

  • wpml flags
  • 2

How to make a shortcode for WPML language flags.

To display the language flags in a shortcode, use the function below.

Use the following shortcode where you want the flags to appear.

[wpml_shortcode_lang]


VERSION 1
Use this version to simply swap out the icon, however, the icon will be very small.

###########################
//WPML language flags in shortcode
//see: https://www.jucra.com/whmcs/knowledgebase/161/
###########################
add_shortcode( 'wpml_custom_lang', 'wpml_shortcode_lang' );
function wpml_shortcode_lang() {
 
    $languages = icl_get_languages('skip_missing=0');
 
    if( 1 < count( $languages ) ) {
        $s = "";
        foreach( (array)$languages as $language ) {
            $s .= '<span><a href="' . $language['url'] . '"><img src="' . $language['country_flag_url'] . '" alt="" /> ' . $language['native_name'] . '</a></span> ';
        }
    }
 
    return $s;
}

Version 2
This function allows a bit more creativity with the flags but you have to rely on hand-coding the languages and their image location.

If you see below, you can see the variables for $flag_url are hardcoded in to the function.

However, using the class: header-lang-flags yiou can manipukate things a bit.

###########################
//WPML language flags in shortcode
//see: https://wpml.org/forums/topic/shortcode-to-place-the-language-flags/
###########################
add_shortcode( 'wpml_custom_lang', 'wpml_shortcode_lang' );
function wpml_shortcode_lang() {
 
    $languages = icl_get_languages('skip_missing=0');

        foreach( (array)$languages as $language ) {
            
            if( 1 < count( $languages ) ) {
                
                //$s = "";
                $flag_url = "";
                $lang_code = $language["code"];

                if($lang_code == "en") { $flag_url = "/wp-content/uploads/2020/08/en-flag-50x35-1.png"; }
                if($lang_code == "es") { $flag_url = "/wp-content/uploads/2020/08/es-flag-50x35-1.png"; }
                if(empty($flag_url)) { $flag_url = $language['country_flag_url']; }
                
                $s .= '<span class="header-lang-flags '.$lang_code.'"><a href="' . $language['url'] . '"><img src="' . $flag_url . '" alt="" /> ' . $language['native_name'] . '</a></span> ';
            
        }
    }
 
    return $s;
    
}

Drop this into your css stylesheet to change the layout to like below.

.header-lang-flags img{
	float:right;
	width:50px;
	margin-left:15px;
}


Was this answer helpful?

« Back