Simple language switcher for WordPress with the free version of Polylang

Building a multilanguage website with WordPress is not as easy as one might think. I’ve decided to build this one using the free version of the Polylang plugin.

Refusing to pay for the pro version of this plugin, I had to do the following to get a simple language switcher:

  • write a new function returning this switcher and
  • define s shortcode to insert in the block editor.

The function (placed in the theme’s function.php file) is:

if (function_exists('pll_the_languages')):
	function clapup_langselector($atts){
    	$thelanguages = pll_the_languages( array('raw' => 1) );
	 	$languages = [];
			  
		foreach($thelanguages as $language) {
	   		array_push($languages, $language);
	 	}
		  
	 	ob_start(); ?>
			<span>
			<?php foreach($languages as $language) { ?>
            	<span>
					<a href="<?php echo($language[url]); ?>" rel="alternate" hreflang="<?php echo($language['slug']) ?>">
						<img src="<?php echo($language['flag']); ?>" width="20" style="padding: 10px" alt="<?php echo($language['name'])?>"></a>
				</span>
			<?php
			}?>
			</span>

		<?php return ob_get_clean();
	}
endif;

The shortcode is then added by the line:

add_shortcode('langselector', 'clapup_langselector');
  • Checking whether the pll_* function exists is mandatory.
  • The end of the <a> tag has to be on the same line as the <img> tag otherwise gets whitespace is inserted in the html.
  • I’ve chosen the output buffer approach because for better maintainability, as it yields correctly highlighted code.

The language selector can then be easily added through the block editor by inserting the following shortcode:

[langselector]

Voilà:


Posted

in

by

Tags:

Comments

Leave a Reply

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