How to add pages to custom menus on the fly

My theme has a custom menu called “Custom Header Menu” and i’ve got a plugin that sets up site defaults and creates my static pages that I’d like to customize in order to seed the custom menu with posts and pages on the fly.

So I’d like to add some code to the plugin so that each of the page’s I’m creating gets added/assigned to the custom menu.

Read More

I’m just looking for a point of reference on how to add pages to a custom menu on the fly via script…

From wp-includes/nav-menu.php, I’m expecting to use this…

wp_update_nav_menu_item( $menu_id = 0, $menu_item_db_id = 0, $menu_item_data = array() )

Where $menu_id is the id of my “Custom Header Menu” and $menu_item_data is an array of the pages I’m assigning to the menu.

Related posts

Leave a Reply

2 comments

  1. I guess it doesn’t need anymore explanation:

    $mymenu = wp_get_nav_menu_object('Main Navigation Menu');
    $menuID = (int) $mymenu->term_id;
    $myPage = get_page_by_title('About Us');
    
    $itemData =  array(
        'menu-item-object-id' => $myPage->ID,
        'menu-item-parent-id' => 0,
        'menu-item-position'  => 2,
        'menu-item-object' => 'page',
        'menu-item-type'      => 'post_type',
        'menu-item-status'    => 'publish'
      );
    
    wp_update_nav_menu_item($menuID, 0, $itemData);
    
  2. Can you post the name of your plugin? Maybe someone has already a solution for this specific question.

    I cannot give u a solution. Haven’t much played around with the “new” wp-navmenu feature so I can only make some suggestions:

    1. Search in your plugin for the function/method which creates a new post in the WordPress table.
    2. Return the id of the created post (wp_insert_post(), wp_update_post() returns it by default).
    3. Add the post with the given id to the menu:
      • With a post in wp_posts table – The wp-nav-menu items are simple posts with post type “wp-nav-item”. You also need to add the right terms and make the relationship in the wp_term_relationships table.
      • With a filter-hook, e.g. ‘wp_get_nav_menu_items’. Look at the file “nav-menu.php” in the wp-includes directory. On line 525 you could see the assigned filter-hook in the function “wp_get_nav_menu_items”. This method wouldn’t be parmanent, which meens you cannot edit the posts/pages in the “Menu”-Section in your Adminpanel. So option Nr.1 is probably the way to go for your problem.