WPML Languages

Living in Montreal, I often have to create multi-lingual websites for clients. That means finding the right plugin for the job. I don’t always use WPML, but it’s one of my go-to plugins when it comes to creating websites with multiple languages.

A recent client requested that their site display a different logo for each language. In order to make this happen, I had to code a simple conditional statement using PHP. But I needed to know which language was selected to display the right logo.

I wasn’t sure if WPML stored the current language selection so I had to do a bit of research. Thankfully, I discovered it did.

The Language Code

When a visitor selects a language, a two-letter language code is stored in the constant ICL_LANGUAGE_CODE. Using this and a little PHP, I wrote the following block of code to give my client what they wanted.

<?php if ( defined( 'ICL_LANGUAGE_CODE' ) && 'fr' == ICL_LANGUAGE_CODE ) { // If the language is French ?>
	<img src="<?php echo esc_url( get_template_directory_uri() ); ?>/images/fr_logo.png" class="site-logo" alt="" />
<?php } elseif( defined( 'ICL_LANGUAGE_CODE' ) && 'it' == ICL_LANGUAGE_CODE ) { // If the language is Italian ?>
	<img src="<?php echo esc_url( get_template_directory_uri() ); ?>/images/it_logo.png" class="site-logo" alt="" />
<?php } else { // If the language is English, the default ?>
	<img src="<?php echo esc_url( get_template_directory_uri() ); ?>/images/en_logo.png" class="site-logo" alt="" />
<?php } ?>

I placed that in header.php and used the class site-logo to style the CSS to match the client’s requested design.

Is there a better way?

If you take a closer look at the code above, you’ll notice that all the filenames have the language code as a prefix. That means you can simplify things even more which is always a better approach when it comes to coding.

<?php $lang_prefix = ( defined( 'ICL_LANGUAGE_CODE' ) ) ? ICL_LANGUAGE_CODE : 'en'; ?>
<img src="<?php echo esc_url( get_template_directory_uri() ); ?>/images/<?php echo esc_attr( $lang_prefix ); ?>_logo.png" class="site-logo" alt="" />

Using the WPML plugin’s ICL_LANGUAGE_CODE constant lets you create all kinds of custom code specific to each language. Displaying different logos is just the tip of the iceberg.

NOTE: Konrad from WPML mentioned in a comment below a better way to get the current language code. It’s probably a good idea to use that one instead.