I am trying to make a basic plugin and want to add or remove sub menu item on plugin activation or deactivation. I am trying to achieve this with wp_get_nav_menu_items()

   $menuLocations = get_nav_menu_locations();
   $menuID = $menuLocations['primary']; 
   $primaryNav = wp_get_nav_menu_items($menuID);

I have three menus Home About product. I want to add a submenu under product on plugin activation.


1 Answer 1


If you want to add items dynamically at every page call, you can look this answer :
Dynamically add sub-categories to any category in the menu

And to add an element directly, you can try that for a custom link e.g. :

// create the new element

$post = [
    'post_title' => "StackExchange " . date("H:i:s"),
    "menu_order" => 700, // position in the menu
    'post_type' => 'nav_menu_item',
    'post_status' => 'publish',

$menu_item_db_id = wp_insert_post( $post );

update_post_meta( $menu_item_db_id, 'url', "https://wordpress.stackexchange.com/");
update_post_meta( $menu_item_db_id, 'type', "custom");
update_post_meta( $menu_item_db_id, '_menu_item_menu_item_parent', 0); // change to create a sub menu

// association to the menu

$menuLocations = get_nav_menu_locations();
$menuID = (int) $menuLocations['primary'];

wp_set_object_terms($menu_item_db_id, $menuID, "nav_menu");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.