Add a Custom Wordpress Menu Item by Code
If you want to add a custom WordPress menu item by code, you can use the code below:
$menu_id = 11;
$menu_item_id = 0;
$params = array(
'menu-item-type' => 'custom',
'menu-item-url' => 'https://example.com/',
'menu-item-title' => 'Link Title',
'menu-item-status' => 'publish'
);
wp_update_nav_menu_item( $menu_id, $menu_item_id, $params );
If $menu_item_id is 0, a new menu item will be created. If you specify a specific ID instead, the menu item with this ID will be updated.
Add a Page to the Menu
If you want to add a WordPress page to the menu, you can use the code below:
$menu_id = 11;
$page_id = 22;
$menu_item_id = 0;
$params = array(
'menu-item-object-id' => $page_id,
'menu-item-object' => 'page',
'menu-item-status' => 'publish',
'menu-item-type' => 'post_type',
);
wp_update_nav_menu_item( $menu_id, $menu_item_id, $params );
You have to customize $page_id and specify by $menu_item_id, if a new menu item should be created or an existing one should be updated.
Related Posts
- Remove All Items from a Wordpress Navigation Menu by Code
- Avoid WPForms Spam by Implementing a Custom Honeypot
- Add Custom CSS Styles to WordPress Visual Editor
- Menu shortcode
- Configure WordPress Backend Search to Search Titles Only
- Always Show the "Read More" Link When Using the Astra Theme
- Disable Hover Menu in Genesis