Answers for "Adding a custom item to a specific place in the menu"

PHP
0

Adding a custom item to a specific place in the menu

add_filter( 'wp_nav_menu_primary-menu_items', 'prefix_add_menu_item', 10, 2 );
/**
 * Add Menu Item to a specific place in the menu
 */
function prefix_add_menu_item ( $items, $args ) {
        
$items_array = array();
        while ( false !== ( $item_pos = strpos ( $items, '<li', 10 ) ) ) // Add the position where the menu item is placed
        {
            $items_array[] = substr($items, 0, $item_pos);
            $items = substr($items, $item_pos);
        }
        $items_array[] = $items;
        array_splice($items_array, 9, 0, '<li class="menu-item">...</li>'); // insert custom item after 9th item one

        $items = implode('', $items_array);
       
       return $items;
}
Posted by: Guest on October-26-2021

Code answers related to "Adding a custom item to a specific place in the menu"

Browse Popular Code Answers by Language