How To Add Custom Menu Position in WordPress
Once upon a WordPress time, I had a unique challenge. A client wanted a custom Bootstrap menu with special JS and CSS, and they’d found the perfect design on Codepen.io. The catch? They wanted it seamlessly integrated into their WordPress site, and the custom menu item had to snugly fit between two specific menu items.
Fear not, for after a bit of exploration, I uncovered a nifty solution – a WordPress hook trick. No complexities here, just a simple flow to understand.
Step-by-Step Guide: Adding Custom Menu Position
1. Add New Menu at the Very End:
Use this code in your functions.php to add your custom menu as the last item:
function pp_add_last_nav_item($items) {
return $items .= '<li><a href="http://yourwebsite.com/newmenu">New Menu</a></li>';
}
add_filter('wp_nav_menu_items','pp_add_last_nav_item');
2. Position Custom Menu Between Nav Menu Items:
Use the following code in your functions.php to insert your custom menu somewhere between the nav menu:
add_filter('wp_nav_menu_items','pp_add_custom_in_menu', 10, 2);
function pp_add_custom_in_menu( $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;
array_splice($items_array, 2, 0, '<li class="drowpdown">
<a href="#">New Menu <span><i class="fa fa-angle-double-right"></i></span></a>
</li>'); // insert custom code
$items = implode('', $items_array);
return $items;
}
3. Understanding the Code Flow:
- We used
wp_nav_menu_items
filter hook to filter the HTML list content for navigation menus. array_splice
is then utilized to split the menu into arrays. In our case, we call our Custom Menu, “New Menu,” to be positioned after the second item in Nav Menu – making it the third item.
You can tweak the code to position your custom menu anywhere between the nav menus. Give it a try, and you’ll understand the magic!
Conclusion: Enjoy Customized Menus!
And that’s it! You’ve successfully added a custom menu position in WordPress. Feel free to insert your unique HTML code and position it wherever your heart desires.
Got questions or facing issues? Drop a comment below. And if this simple guide added a sprinkle of magic to your WordPress journey, don’t forget to hit that Share button! ✨