Search code examples
phpwordpresswpml

WPML Navigation Menu Location Issue


Context

I was trying to add custom language switching links in the navigation. The problem is I have two menu location header-main and footer-main (These are the menu slugs). But I only want language links in the header-main menu.

Currently the wordpress callback wp_nav_menu_items works fine, but it will add the links processed to all the menu locations. Here is the working code for it:

function icl_post_languages() {
    return icl_get_languages('skip_missing=1');
}

function get_translation_navigation() {
    $nav = '';
    $lang_nav = icl_post_languages();
    if (count($lang_nav) > 0) {
        foreach ($lang_nav as $item) {
            $nav .= '<li>';
            $nav .= '<a href="' . $item['url'] . '">' . $item['native_name'] . '</a>';
            $nav .= '</li>';
        }
    }
    return $nav;
}

add_filter('wp_nav_menu_items', 'add_translation_navigation');

function add_translation_navigation($menu) {
    $language_nav = get_translation_navigation();
    $menu = $menu . $language_nav;
    return $menu;
}

The Issue

But when I change the wordpress filter to:

add_filter('wp_nav_menu_header-main_items', 'add_translation_navigation');

So, that the filter is applied to only header-main menu. It works and fires the filter when current language is English, when the language is switched to Arabic it doesn't fires the filter.

Also, there are two separate menus, one for Arabic and one for English, but location of both is same i.e. header-main


Solution

  • I might be misunderstanding the question, but it looks like you're confusing theme locations and menu slugs regarding the wp_nav_menu_{$menu->slug}_items filter. You could try for example:

    add_filter('wp_nav_menu_items', 'add_translation_navigation', 99, 2 );
    
    function add_translation_navigation( $menu, $args )
    {
        if( 'header-main' == $args->theme_location )
            $menu .= get_translation_navigation();
    
        return $menu;
    }
    

    to check for the specific header-main theme location.