Can I add pages to my custom menu via script?

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 🙂

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x