How to change menu according to the language?

This can be done via cookies.
We set it with Javascript, reload the page and display different menus in PHP using its value.

First, print the script at the site footer (see comments).
Note: would be better to enqueue this together with your theme scripts.

add_action( 'wp_footer', 'wpse_77220_language_cookie' );   
/**
 * Cookie script based on http://github.com/bainternet/Admin-Page-Class
 */
function wpse_77220_language_cookie()
{
    echo '<script>
    /* Set Cookie */
    function setCookie( name,value,days ) 
    {
        if (days) 
        {
            var date = new Date(); 
            date.setTime(date.getTime()+(days*24*60*60*1000));
            var expires = "; expires="+date.toGMTString();
        }
        else var expires = "";

        document.cookie = name+"="+value+expires+"; path=/";
    } 

    /* Get Cookie - not used in this example */
    function getCookie( name ) 
    {
        var nameEQ = name + "=";

        var ca = document.cookie.split(";");
        for(var i=0;i < ca.length;i++) 
        {
            var c = ca[i]; 
            while (c.charAt(0)==\' \') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
        return null;
    }

    /* Erase Cookie - not used in this example */
    function eraseCookie(name) { setCookie(name,"",-1); }

    // Bind click on language menu action to show the nav menu.
    jQuery(document).ready(function() 
    { 
        jQuery(".lingo").bind("click", function(event)
        {
            setCookie( "user_lingo", jQuery(this).attr("id") );
        });
    });
</script>
';
}

If jQuery is not included in your theme:

add_action( 'wp_enqueue_scripts', 'wpse_77220_enqueue_jquery' );   
function wpse_77220_enqueue_jquery() {
    wp_enqueue_script( 'jquery' );
}

Then, in the theme header.php, we put this:

</head>
<?php 
    if( isset( $_COOKIE['user_lingo'] ) ) {
        $user_lingo = $_COOKIE['user_lingo'];
    } else {
        $user_lingo = 'en';
    }
?>
<body <?php body_class(); ?>>

Then, the wp_nav_menu:

<?php wp_nav_menu( array( 'menu' => $user_lingo ) ); ?>

In this example, the navigation menus have the same name of the values we’ll set for the cookie. If your menus have another name, you have to adapt the header conditional for $user_lingo.
navigation menus

Finally, the language menu. The class lingo is binded via jQuery to set the cookie value with the anchors id‘s. The href value forces the page to reload, you can use another method if you wish.

<a href="https://wordpress.stackexchange.com/questions/77220/?lang=pt" id="pt" class="lingo">pt</a> |
<a href="?lang=es" id="es" class="lingo">es</a> |
<a href="?lang=en" id="en" class="lingo">en</a>

Leave a Comment