How to use a custom language switcher with Transposh to build a multi-language WordPress website

In this article you’ll learn how to use a custom language switcher with Transposh to build a multi-language website with WordPress totally free.

When it comes to build a multi-language website, WordPress offers a lot of different plugins: WPML, Polyglot and so on.

All these plugins have a free version with relevant limitations: if you want a fully functional plugin you must buy the Premium version.

But this is not true for Transposh: Transposh is totally free, forever, without any limitation (in number of languages, number of websites or anything else). And it works great:

  • install Transposh and activate it
  • set your default language in Worpdress Settings->General section
  • choose the languages you want to use in Transposh->Languages
  • In Transposh->Settings set who can edit translations (tipically they will be Administrators and Editors)
  • Enable url rewriting
  • Set WordPress Settings->Permalink to Post name (/%postname%/)
  • that’s all. Your text will be automatically translated in the selected language

In addition, Transposh let you fix any translation error in a quick and easy way! So I’ll show you How to use a custom language switcher with Transposh to build a multi-language website with WordPress.

But… Always there is a “but” ๐Ÿ™‚ First, to use the full widget you must upgrade to fully version: no problem, is free.ย  Go to Transposh section of the dashboard and choose Settings, then check the “Allow upgrading to full version from http://transposh.org, which has no limit on languages used and includes a full set of widgets” checkbox and click Save changes button. After some time you’ll be notified there is an update available for Transposh: update and you are ok.


Once Transposh has been updated to the full version, you finally get the widget and… As usually, it happens that the widget probably doesn’t integrate in your website design, requiring a lot of work to add custom CSS, trying to style it in a coherent way with the rest of your styles. And last but not least, English language is represented by the United States flag! Don’t know why, after all english is english and it was born in UK. So, what to do? Well, we’re going to build our custom language switcher.

 

What exactly we need?



Let’s see how Transposh works. When you click on the flag of a non-default language, Transposh reloads the page and changes its own aspect. As you can see, a checkbox appears immediately under the flags: checking it will reloads the page in Edit mode. Depending on Transposh settings (leave them to default if you don’t have any specific issue with this), every text in the page will have a small yellow button appended: clicking on that button will show a popup to edit the translation or just approve them (approved translations will have a green button instead of a yellow one)

So, summarizing, first we have to provide our user an easy and possibly beautiful way to switch between languages; secondly, we have to provide to administrators and editors a quick way to put the website in edit mode to fix translations’ errors. To do this will follow these steps:

  • we’ll set some WordPress setting
  • we’ll upload to our WordPress installation the flags’ images we need
  • we’ll install a couple of plugins
  • we’ll write a bit of codeCustom language switcher step by step

 

 

Custom language switcher step by step

Step 1: WordPress settings

First, as I said before, go to Settings->Permalink and set it to Post name (%postname%).

Then, go o Appearance->Menus, open Screen options clicking on the top-right tab and check the CSS Classes checkbox as shown in the image below.

 

Step 2: the flags

First we need to get our flag icons. Just google a bit and you’ll find a lot of free flag icons sets: choose your favorite one download it and upload the flags to your website using the Media section of WordPress dashboard. In thus article I’ll use three flags, english, spanish (because I live in Spain) and italian (because I’m from Italy), but obviously feel free to use the flags you really need to use.

Step 3: some plugins

In order to use our flags we’re going to use a couple of useful plugins (even these ones are totally free).

Plugin 1: Menu Icon by ThemeIsle

This small adorable plugin (https://wordpress.org/plugins/menu-icons/) allows you yo set any icon or image you want to associate it to a menu item. The plugin allows to choose if the menu item text must be visible or hidden, so we can add to our menu the 2 flags quickly and easily.

That’s all for now.

Plugin 2: If Menu

Now we have to add another menu item to switch on or off the option to edit the translation if we are not to happy with it. This function works out of the box with Transposh widget but since we’re not using it we’ll have to implement it manually.

Technically, the If Menu plugin is not strictly necessary: I use it because I don’t want visitors can change the website text as they want and I suppose that the majority of you will do the same. If Menu plugin just do this: it allows to add a conditional logic so you can show or hide single menu items depending on the user’s role.

Step 4: building the menu

Okay, now we’re ready to build our menu. Go to Appearance->Menus.

Settings for Menu Icon

When you are in Menus section, you’ll see a new element in Add menu items left side bar: Menu Icon Settings. Open it, uncheck the pre-selected option Dashicons (we don’t need it) and check the Images option like in the image to the left.

 

Then switch to the Current Menu tab and set Hide Label to Yes. Finally, just Save Settings!

Once we have completed these preliminary tasks, we can start to add menu items to our menu.

Adding the language switcher’s menu items

We’ll add 3 menu items with the flags to allow users to switch between our three supported languages. Then we’ll add a fourth item to enable/disable translation editing (for this menu item we’ll use the conditional logic offered by If Menu plugin. For each menu item we’ll use Custom links.

The image below shows you how to set the menu item for your default language (in our case it will be english). Choose Custom links as Menu item type, type the base url of your website as URL and ‘en’ (without quotes) as Link text.

Yes, it’s true! I’m implementing multilanguage feature for this blog writing this article: thrilling, isn’t it?

Okay, now the menu item should look like this:

Do you see? There is a row which says Icon: Select. Click on Select to upload your flag (or to select it from you Media library if you had already uploaded it).

 

Do you see the Union Jack?

Now, in the input box CSS Classes (optional) type ‘no_translate’ (again, without quotes).


Do the same for each language you want to use. The only thing you have to change is the URL in your Custom link: add ‘/it’ for italian, ‘/es’ for spanish and so on…


Save you menu and take a look at your website: it is already a multi-language website!!!

Creating the “Edit mode” menu item

But automatic translations are often poor, so we need a way to change and correct them. To do this, we’ll add a new Custom link to our menu: I called it Edit on/off. We won’t put anything in URL field and we’ll have to check the ‘ Enable visibility rules ‘ checkbox to make this item visible only to Administrators and to Editors. In addition, we have to add the class ‘edit-translation’ which we’ll use to handle the click event and enable the edit mode (as you can see I also attach the no-translate class here since I don’t need to translate this item).

Notice: this menu item will appear only when you browse the website in a secondary language: Transposh is smart enough to know that there is no translation to fix for the default language!

But this item has no URL, so it won’t do anything… To make it work we have to write a bit of javascript.

Step 5: a bit of coding

So we have our main menu with 3 flags (that already work fine: just give it a try) and the Edit on/off item to enable the manual editing of the translated text; this last menu item will be visible only if the user will be logged as Administrator or Editor.

But in order to make this menu item work correctly we need to add some javascript. Run your editor code of choice and create a new file; then write in this code:

jQuery(document).ready(function($) {
    var urlParam = function (name) {
        var results = new RegExp('[?&]' + name + '=([^&#]*)').exec(window.location.search);
        return (results !== null) ? results[1] || 0 : false;
    }
    $(document).on('click', '.edit-translation', function(e){
        e.preventDefault();
        var currentOrigin = window.location.origin;
        var currentPath = window.location.pathname;
        var param = urlParam('tpedit');
        var newUrl = '';
        if (param === false){
            newUrl = currentOrigin + currentPath+'?tpedit=1';
            $(this).attr('href', newUrl);
        }else{
            newUrl = currentOrigin + currentPath;
            $(this).attr('href', newUrl);
        }
        window.location.href = newUrl;
    })
})

Quick explanation: when the user clicks on our menu item ‘Edit on/off’, first we prevent the default event, that is reload the current page. Then the code uses window.location.origin and window.location.pathname to get the current base URL and current path.

For instance, if we are in http://codingfix.com/how-to-use-custom-flags-languages-switcher-with-transposh/ currentOrigin will be http://codingfix.com whereas currentPath will be how-to-use-custom-flags-languages-switcher-with-transposh/. But if we were in http://codingfix.com/es/how-to-use-custom-flags-languages-switcher-with-transposh/, currentPath would be es/how-to-use-custom-flags-languages-switcher-with-transposh/.

Once we have the components of the current url we check if the string ‘tpedit’ is present in the url as a parameter. This parameter is used by Transposh to enable edit mode for translations: when you use the widget and check the Edit translation checkbox the page is reloaded with the param ‘tpedit=1’ appended to the URL. So we have to check if we are in edit mode: if we are, we create a new URL using only currentOrigin and currentPath and we redirect the browser to this URL (that is we reload the page removing the param ‘tpedit’); otherwise, we build the new URL appending the param ‘tpedit=1’ and reload the page in edit mode.

Now save the file with the name you prefer: I’ll use the name ‘myscript.js’ because I’ve no time to waste thinking to a nicer name ๐Ÿ™‚

Now we have to upload this file into our theme folder, preferably in a subfolder called ‘js’. By the way, I strongly recommend you to use a child theme because any change you do to the theme files will be lost when the theme will be updated (if you don’t know what is a child theme you can read this: https://www.wpbeginner.com/beginners-guide/wordpress-child-theme-pros-cons/ To easily create a child theme from your current theme you can use the plugin Child Theme Configurator).

Step 6: loading our script

Now we have to modify the file functions.php in order to load our script. The code to be used is slightly different depending on wheter you use a child theme or not.

If you are using a child theme (recommended) you have to add to you functions.php the following code:

function load_custom_javascript() { 
    wp_enqueue_script( 'myscript', //script name
        get_stylesheet_directory_uri() . '/js/myscript.js', //complete path to the file
        array('jquery'), //array of dependencies
        '', //version number
        true //put script in footer
    ); 
}
add_action( 'wp_enqueue_scripts', 'load_custom_javascript' );

If you love to live dangerously and you’re not using a child theme, just replace get_stylesheet_directory_uri() with get_template_directory_uri().

Finally, we’ve got it!

Okay, that’s all folks! Now you can start to fix automatic translations. Me too, I fear…

19 thoughts on “How to use a custom language switcher with Transposh to build a multi-language WordPress website”

  1. Wow. Thank you so much!. This is just what I was looking for. Amazing!! Didn’t get the edit translation to work. The dot is disappearing when menu is saved. But I gues I’ll just place the original menu somewhere else to be able to edit…

    1. Hi Lars. Thank you for reading and forgive for the delay replying to your comment.
      Well, the dot is a my error: thank you for pointing it out Iโ€™ve already fixed the text and the screenshot. Actually, we donโ€™t have to put the dot โ€“ WP is smart enough to know that CSS classes are prefixed with a dot;)
      So you should be able to get it working as it is, without any dot for the edit-translation class.
      Also, I’m writing a small plugin to add the Edit translation button and make it work, so stay connected!
      Let me know if youโ€™ve got it working fine, Iโ€™d be glad to help you!

  2. Awesome tutorial! Thank you!
    Just a quick question though, do you know a way to automatically change the Menu when you change language?
    e.g EN is my default and ES is my other language. I have “ES” button on my main menu and I want it to automatically chang to EN whenever they press it and go to the ES site.

    Appreciate it a lot.
    Thanks

    1. Hi Clarence.
      Interesting question. I have never thought about that. In general, I think you could do it with some javascript changing only one meun item instead of the whole menu. You should add a class to your languages menu items and then manage the click event… I’m really toobusy in this period to work on that but I’ll keep it in mind.
      Please, let me know if you get the solution: I’ll be happy to integrate it in the post adding you as contributor ๐Ÿ™‚
      Cheers

    1. Hello Andrew. Thank you for using Language Switcher for Transposh. I need to clarify that my plugin doesn’t translate anything: translations are a Transposh plugin responsability so I couldn’t help about this. You can try to ask at https://transposh.org. My plugin just provide a language switcher but it has nothing to do with the translation itself. I’m sorry I can’t help you here. Cheers

  3. I am extremely impressed with your writing skills and
    also with the layout on your blog. Is this a paid theme or did you
    customize it yourself? Anyway keep up the excellent quality writing, it’s rare to see a nice blog like
    this one nowadays.

  4. Hey this is kinda of off topic but I was wondering if blogs use WYSIWYG editors or
    if you have to manually code with HTML. I’m starting a blog soon but have no
    coding knowledge so I wanted to get guidance from someone with experience.
    Any help would be enormously appreciated!

    1. Hi Robbie. Just use WordPress: it lets you to do anything without writing a single line of code. But it also allows you to write your code, if you want ๐Ÿ™‚

  5. Hi Marco, I tried the Transposh Language switcher plugin, but it seems not to work with the Avada theme, even though I am using a Child Theme. So, I decided to follow your tutorial and created it from scratch. It works, but I cannot get the Edit on/off part working. I did everything as per your clear and well-written tutorial. Would this be a conflict with the Plugin? I will disable the language switch plugin and see if it works.

    1. Hello Eddie, thank you for trying my plugin and I apologize for the inconvenient. I’d appreciate you could be more precise about what gone wrong with Avada, but I’ll do some test to check that.
      About the Edit On/Off from the tutorial, keep in mind that this part depend on javascript so you have to clear the browser cache to be sure the javascript be loaded. Also remember that EDIT button will only be visible after you have switched to a translated language: we presume that the original text will be edited directly in the WP posts/pages, so only the translations will be editable.
      If you have enabled WP_DEBUG, in wp-content folder you’ll find the file debug.log which can give you precious information. If you don’t know how to activate debug in WordPress, just connect to your website via FTP and download the file located in the root directory called wp-config.php. Alternatively, you can locate and edit this file through your Administrative Panel (cPanel, Plesk or so) using the File Explorer.
      Once you have opened the file Look for the foloowing line of code:

      define( ‘WP_DEBUG’, false );

      and replace it with the the following lines:

      define( ‘WP_DEBUG’, true );
      define( ‘WP_DEBUG_LOG’, true );
      define( ‘WP_DEBUG_DISPLAY’, false );
      @ini_set( ‘display_errors’, 0 );

      With WP_DEBUG enabled you can retest my plugin with Avada and see if in the debug.log file you find some useful information. If you share it with me I’ll be happy to help.
      Keep in mind that the plugin has been updated many times from the time of writing that tutorial and using it grant you to get any next update and improvement.
      Hope this help you
      Cheers

    2. Okay, I see Avada leaves empty the item “theme_location” of $args array passed to the filter wp_nav_menu (orwp_nav_menu_items). LSFT uses theme_location to set where to put the language switcher accordingly to its own settings: it does a simple check to see if the menu theme_location is equal to the menu_location chosen by the user. If the theme_location is not specified in $args array, LSFT just remains inactive. Looking for a solution or at least for a workaround.

    3. Hi Eddie.
      For the moment it looks like I can’t fix the issue because in my plugin theme_location for the menu is empty. But, if you want, you can use LSFT shortcodes in your menu too. Just install Shortcode in menus plugin (https://wordpress.org/plugins/shortcode-in-menus/). Then in Appearence->Menus page you’ll see that you have the option to insert in the menu a shortcode: leaves the title blank and put the LSFT shortcode you prefer. Maybe you might want to adjust the css (but I have already released a new version where I have fixed a css issue in shortcode for a flag switcher).
      Let me know if this helps ๐Ÿ™‚
      Thank you

      1. Hi Marco Gasi, thanks for the quick reply. I will try it and let you know the outcome.
        In this case, I will use the LSFT plugin intead, and see what happens. Thnaks.

  6. Hi Marco,
    I got the flags on the menu per your instructions, using the shortcakes after installing the “Shortcode in menus” plugin.
    Marco, just an update: It also took care of the edit part. Awesome! For the Avada users, just using the Shortcode in menus solves the problem. There will be an issue, though. I need to disable the Transposh plugin if I need to use Avada Live Builder, which I find OK. So, the big problem has been solved.
    Best regards,

    Eddie Fontes
    Check my website: https://revistaamericandream.com
    Suggestions accepted.
    Thanks a lot.

Leave a Comment

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