Add wordpress menu items programatically

Often we come across situations where we need to add wordpress menu items programatically, based on some condition. This condition could be anything like displaying a logout link in menu if a user is logged in the site or displaying different menu items based on user roles. This can be accomplished by using wordpress filters using following snippet.

Add wordpress menu items programatically

// first create a function
function at_custom_menu_item($menu_items) {
$new_item = '<ul>
<li class="new-item"><a href="' . $place_your_link_here . '">' . __('New Item') . '</a></li>
</ul>';
// add the custom item to the end of the menu
$menu_items = $menu_items . $new_item; return $menu_items; }

//Now use the 'wp_nav_menu_items' fillter to display menu item in menu.

add_filter( 'wp_nav_menu_items', 'at_custom_menu_item' );

//Above code will place the new item in every menu, if you wish to add this item only to a selected menu, use following

add_filter( 'wp_nav_menu_{$menu->slug}_items', 'at_custom_menu_item' );