Skip to content

Instantly share code, notes, and snippets.

@jeffrainey
Created August 20, 2015 18:22
Show Gist options
  • Save jeffrainey/3b78740a8c4c1738cab9 to your computer and use it in GitHub Desktop.
Save jeffrainey/3b78740a8c4c1738cab9 to your computer and use it in GitHub Desktop.
Create a menu item using wp_get_nav_menu_items. This simply adds the item to the end. The cool thing it appears in the menus editor too! It would be nice to add ability to sort in the menu and remove the item using the menu editor.
// from http://www.daggerhart.com/dynamically-add-item-to-wordpress-menus/
add_filter( 'wp_get_nav_menu_items', 'custom_nav_menu_items', 20, 2 );
function custom_nav_menu_items( $items, $menu ){
// only add item to a specific menu
if ( $menu->slug == 'secondary-navigation' ){
// only add profile link if user is logged in
if ( get_current_user_id() ){
$items[] = _custom_nav_menu_item( 'Logout', wp_logout_url( '/' ), 3 ); //log user out and drop them on the home page
}
}
return $items;
}
/**
* Simple helper function for make menu item objects
*
* @param $title - menu item title
* @param $url - menu item url
* @param $order - where the item should appear in the menu
* @param int $parent - the item's parent item
* @return \stdClass
*/
function _custom_nav_menu_item( $title, $url, $order, $parent = 0 ){
$item = new stdClass();
$item->ID = 1000000 + $order;
$item->title = $title;
$item->url = $url;
$item->menu_order = $order;
$item->menu_parent_item = $parent;
$item->type = '';
$item->object = '';
$item->object_id = '';
$item->db_id = '';
$item->classes = array();
return $item;
}
@aartjan
Copy link

aartjan commented Jan 9, 2021

I think line 33 should be

$item->menu_item_parent = $parent;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment