2016-01-13 119 views
0

我需要通过函数添加一个项目到一个特定的子菜单,我该怎么做?我做了一个简短的草图来显示我需要什么,谢谢你的帮助!WordPress的:添加项目到子菜单

素描:

add_filter('wp_nav_menu_items','specialprojekte_in_projekte_submenu', 10, 2); 
function specialprojekte_in_projekte_submenu($items, $args) { 
    if(???SUBMENU == PROJECTS ???)   
     $items .="<li> this is a special project at the end of projects submenu </li>";   
    } 
    return $items; 
} 
+0

你能描述你想要达到什么样的菜单结构?你想添加这个新项目作为菜单上的子菜单,或作为子菜单上的子菜单... – pgk

+0

使用定制的沃克级代替..更容易添加 –

+0

我想添加这个新的项目到现有的子菜单... – buckdanny

回答

0

如果你要使用过滤器来修改菜单,在女巫的过滤器必须挂钩是wp_get_nav_menu_items

add_filter('wp_nav_menu_items','specialprojekte_in_projekte_submenu', 10, 2); 

在这个钩子第一个参数给你所有菜单元素作为数组。每个菜单元素WP_Post_Object与性能:

WP_Post Object 
(
    [ID] => 6 
    [post_author] => "1" 
    [post_date] => "2015-12-06 19:07:48" 
    [post_date_gmt] => "2015-12-06 17:07:48" 
    [post_content] => "" 
    [post_title] => "Post Title" 
    [post_excerpt] => "" 
    [post_status] => "publish" 
    [comment_status] => "closed" 
    [ping_status] => "closed" 
    [post_password] => "" 
    [post_name] => "221" 
    [to_ping] => "" 
    [pinged] => "" 
    [post_modified] => "2016-01-13 14:05:51" 
    [post_modified_gmt] => "2016-01-13 12:05:51" 
    [post_content_filtered] => "" 
    [post_parent] => "220" 
    [guid] => "http://yoursite.dev/?p=6" 
    [menu_order] => 1 
    [post_type] => "nav_menu_item" 
    [post_mime_type] => "" 
    [comment_count] => "0" 
    [filter] => raw 
    [db_id] => 6 
    [menu_item_parent] => "5" 
    [object_id] => "6" 
    [object] => "custom" 
    [type] => "custom" 
    [type_label] => "Menu Label" 
    [title] => "First Submenu Item" 
    [url] => "http://yoursite.dev/" 
    [target] => "" 
    [attr_title] => "" 
    [description] => "" 
    [classes] => Array 
    [xfn] => "" 
) 

所以,你可以使用所有这些属性的选择上要追加新要素菜单或子菜单。注意如果菜单有"menu_item_parent" <> 0那么这是子菜单。

然后你必须创建你的子对象:

function specialprojekte_in_projekte_submenu($items, $menu) { 
    $menu_cnt = count($items) + 1; 

    //find parent menu item, in witch we wont to append our new menu 
    $parent_id = 0; 
    foreach ($items as $item) { 
     //one possible argument to find what you need 
     if ($item->menu_item_parent === "201") { 
      $parent_id = $item->ID; 
      break; 
     } 
    } 

    $items[] = (object) array(
     'ID'    => $menu_cnt + 100000, // Some big ID that WP can not use 
     'title'    => 'My new submenu', 
     'url'    => '#', 
     'menu_item_parent' => $parent_id, 
     'menu_order'  => $menu_cnt, 
     // These are not necessary, but PHP throws warning if they dont present 
     'type'    => '', 
     'object'   => '', 
     'object_id'   => '', 
     'db_id'    => '', 
     'classes'   => '', 
     'post_title'  => '', 
    ); 
    return $items; 
} 

当然,你可以使用Walker_Nav_MenuCodex

+0

非常感谢为此出色的帮助! – buckdanny