Dev Notes

Various Cheat Sheets and Resources by David Egan/Carawebs.

Inject Menu Item into a Specific WordPress Menu


Navigation, WordPress
David Egan

The ‘wp_nav_menu_items’ WordPress filter allows you to filter the HTML list content for nav menus.

The filter can accept up to two parameters:

  • The HTML list content (<li>s)
  • An object containing wp_nav_menu() arguments

Passing in the second parameter allows you to target the nav menu. The following code appends a new menu item to the ‘Primary Navigation’ menu:

<?php
add_action ('wp_nav_menu_items', function( $menu_items, $menu_object ){

  $menu_name = $menu_object->menu->name;

  // Only append the new li to the 'Primary Navigation' menu.
  // Change 'Primary Navigation' for the name of the menu that you'd like to amend.
  if ( 'Primary Navigation' === $menu_name ) {

    $new_li = "<li><a class='btn btn-default' href='#'>The New Link</a></li>";

    return $menu_items . $new_li;

  }

}, 10, 2 );

References


comments powered by Disqus