Can I add pages to my custom menu via script?

The question:

My theme has a custom menu assignment…

function my_register_my_menus() {
  register_nav_menus(
    array('header-menu' => __( 'Custom Header Menu' ) )
  );
}

…and I’m creating an “installer” type plugin that, upon activation, I would like to hook into this custom menu and assign some pages to it as if they had been created manually.

However, the menu API is pretty new and to date, I’ve been unable to find any examples of how to do this.

I’m hoping someone here can give me some direction, examples or info on how to do it.

Thanks in advance 🙂

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

You can use wp_nav_menu_{$menu->slug}_items hook and add you link with a callback function, for example if your menu slug is header-menu then something like this:

add_filter('wp_nav_menu_header-menu_items', 'add_my_extra_links',10,2);
function add_my_extra_links($items, $args) {
  $newitems = '<li><a title="Test Link" href="http://google.com" rel="nofollow noreferrer noopener">Google</a></li>';
  $newitems .= '<li><a title="Test Link" href="http://yahoo.com" rel="nofollow noreferrer noopener">Yahoo</a></li>';
  $newitems .= '<li><a title="Test Link" href="http://bing.com" rel="nofollow noreferrer noopener">Bing</a></li>';
  $newitems .= $items;
  return $newitems;
}

Update

I guess you would need to call wp_save_nav_menu_items which is the function used to save the menu items to the database.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment