Wordpress - How do I programatically insert a new menu item?
Before being printed, all the menu items get run through a filter. You can target the wp_nav_menu_items
filter to tack things on to the menu:
// Filter wp_nav_menu() to add additional links and other output
function new_nav_menu_items($items) {
$homelink = '<li class="home"><a href="' . home_url( '/' ) . '">' . __('Home') . '</a></li>';
// add the home link to the end of the menu
$items = $items . $homelink;
return $items;
}
add_filter( 'wp_nav_menu_items', 'new_nav_menu_items' );
Or, to be more specific, you can target only the desired menu by replacing the add_filter
line from above with the following, and replacing $menu->slug
with your menu's actual slug name:
add_filter( 'wp_nav_menu_{$menu->slug}_items', 'new_nav_menu_items' );
Source Tutorial