为了解决这个问题,我尝试创建一个插件,如果在菜单中,它会自动为父类别下的发布类别创建菜单项。
插件理念:
1.在代码中,我使用"created_$taxonomy" 行动挂钩。
2.收集所有菜单项(使用wp_get_nav_menu_items)
3.如果发布类别的父级位于菜单项中,而不是创建为其父类别的子菜单的菜单项中,则放置条件。(通过使用wp_update_nav_menu_item)
<?php
/*
Plugin Name: Auto Category Submenu
Plugin URI:
Description: Create menu item when category publish/create if it\'s parent category in menu item.
Version: 0.1
Author: Mayank Gupta/Ravinder Kumar
Author URI:
License: GPL2
*/
class AutoSubmenu {
/**
* Constructor
*/
function __construct() {
add_action( \'created_category\', array( &$this, \'on_publish_cat\' ) );
}
/**
* When publishing a new child page, add it to the appropriate custom menu.
*/
function on_publish_cat( $cat_id ) {
$cat = get_category( $cat_id );
//menu id for you menus in which your sub-category\'s parent category as menu item
$menu_ids = array(101,100);
//retrieve all meu items from menu
foreach($menu_ids as $menu_id){
$menu_items[] = wp_get_nav_menu_items( $menu_id, array(\'post_status\' => \'publish\',\'post_type\' => \'nav_menu_item\',\'output\' => ARRAY_A, ) );
}
foreach($menu_items as $menu_item){
$counter = 0 ;
echo\'<!--\';
print_r($menu_item);
echo\'-->\';
foreach($menu_item as $menu_term){
$menu_terms_id[] = $menu_term->object_id; //all menu items id
}
}
//print_r($menu_terms_id); //test for items in menu
foreach( $menu_terms_id as $menu_term ){
if( $cat->category_parent == $menu_term){
wp_update_nav_menu_item( $cat_id, 0, array(
\'menu-item-object-id\' => $cat_id,
\'menu-item-object\' => $cat->taxonomy,
\'menu-item-parent-id\' => $menu_term,
\'menu-item-type\' => \'category\',
\'menu-item-status\' => \'publish\'
) );
}else{
return;
}
}
}
}
$auto_submenu = new AutoSubmenu();
Note: plugin giving error (header already sent) and menu item not created when category publish.This may be another topic for problem but i put it here because this may be a solution if some suggest me where i am wrong.Sorry if i\'m doing something wrong by putting it here