Wordpress:将项目添加到子菜单

时间:2016-01-13 09:53:50

标签: 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;
} 

1 个答案:

答案 0 :(得分:1)

如果你想使用过滤器来修改菜单,那么必须挂钩的过滤器是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_Menu课程Codex