In the script below, I’m attempting to dynamically add categories to a custom menu. Everything works great, except for the fact that the categories do not have hyperlinks. What am I missing in wp_update_nav_menu_item() below?
$cat_args=array(
'hierarchical' => 0,
'exclude' => '1',
'exclude_tree' => '1',
'hide_empty' => 1,
);
$theCats = get_categories($cat_args);
$name = 'Site Menu';
$menu_id = wp_create_nav_menu($name);
$menu = get_term_by( 'name', $name, 'nav_menu' );
/* insert the a link to home */
wp_update_nav_menu_item($menu->term_id, 0, array(
'menu-item-title' => 'Home',
'menu-item-url' => get_bloginfo('url'),
'menu-item-status' => 'publish')
);
/* insert each category except uncategorized */
if (count($theCats) > 0){
foreach($theCats as $category){
wp_update_nav_menu_item($menu->term_id, 0, array(
'menu-item-title' => $category->name,
'menu-item-type' => 'taxonomy',
'menu-item-status' => 'publish',
'menu-item-object' => 'category',
'menu-item-parent-id' => 0)
);
}
}
theme_set_nav_menu($menu->term_id,'header-menu');
After using the Chrome inspector on the “Appearance > Menus” categories panel I was able to sniff out the hidden form values that are passed when one manually adds a category to a custom menu via the wizard:
So, the resulting script becomes:
I wonder if it needs object id:
Well where you insert the menu items for the categories, your array does not contain the ‘menu-item-url’ key like it does for inserting your home link.
There is the corrected foreach loop