Display custom language switcher in the desired position in menu

By December 4, 2016Tutorials

This article will present a method to display a custom language switcher in the desired position in menu when using WPML plugin for WordPress.

One client wanted the language switcher (with two languages, Romanian and English) to be on the second position in menu and to show just the inactive language.

The initial code for displaying the menu was:

Searching on google how to modify and style the language switcher used in WPML plugin there is an useful link showing how to build your own custom language switcher .

Using these instructions (from section „How to use in your theme functions” in functions.php file from the theme), you have to create a function to build the language switcher:

What the function dose?

1.Get the list of languages from WPML

2. Check if is more than one language for the post

3. Create the output, skipping the currently displayed language

To display it, after the switcher is created, you can save the inactive language returned by the language_selector_in_menu() function in a variable and then you can use it where is needed. For example (as the menu where I had to display the switcher was in header.php) I saved the inactive language returned by language_selector_in_menu() function in $switch_language variable.

To display the switcher in the menu you have to put that variable (in which you saved the inactive language) in the desired position. For this you can use the parameter items_wrap that let you to wrap the list items in menu.
To display the language switcher in the second position, I added the parameter items_wrap to wp_nav_menu()

where the first item is Home, the second is the language switcher that will show the available language for translation and the other items will be pages/links from the menu.

The final code to display the language switcher in the second position in menu is

After you modified items menu you have to synchronize the menu in all language.