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.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top