Search code examples
wordpresswpml

How to add a link to menu before WPML output?


I would like to add a link to a menu programatically. This is simplified version of my code and it works, but WPML adds its language selector on the last place. How can I add my link before WPML output? $items is just a string with all HTML

add_filter( 'wp_nav_menu_items', 'add_search_to_nav', 1, 2 );
function add_search_to_nav( $items, $args ) {

    $items .= '<li><a href="#">Something</a></li>';
    return $items;

}

Solution

  • Use the like as below:

    add_filter( 'wp_nav_menu_items', 'add_search_to_nav', 10, 2 );
    function add_search_to_nav( $items, $args ) {
        $items_array = array();
        while ( false !== ( $item_pos = strpos ( $items, '<li', 3 ) ) ) {
            $items_array[] = substr($items, 0, $item_pos);
            $items = substr($items, $item_pos);
        }
        $items_array[] = $items;
        $new_item = '<li><a href="#">Something</a></li>';
    
        array_splice($items_array, $args->menu->count, 0, $new_item); 
    
        $items = implode('', $items_array);
    
        return $items;
    }
    

    Here $args->menu->count provides the count of menu item without WPML language switcher.