在自定义帖子类型中显示自定义菜单中的当前项目

时间:2012-06-23 作者:pixeline

我有一个自定义的帖子类型“product”。我需要从主菜单访问其索引,因此我添加了一个自定义菜单项,只需将“/works/”作为url值。问题是:如果我查看的是单个产品,则主索引菜单链接不会收到当前的\\u menu\\u祖先类。知道怎么解决吗?

register_post_type( \'product\',      
                array(
            \'labels\' => array(
                \'name\' => __( \'Works\' ),
                \'singular_name\' => __( \'Work\' ),
                \'add_new\' => _x(\'Add New\', \'Work\'),
                \'add_new_item\' => __(\'Add New Work\'),
                \'edit_item\' => __(\'Edit Work\'),
                \'new_item\' => __(\'New Work\'),
                \'view_item\' => __(\'View Work\'),
                \'search_items\' => __(\'Search Works\'),
                \'not_found\' =>  __(\'No Work found\'),
                \'not_found_in_trash\' => __(\'No Work found in Trash\'), 
                \'menu_name\' => \'Works\'
            ),
            \'public\' => true,
            \'publicly_queryable\' => true,
            \'exclude_from_search\'=>false,
            \'show_ui \'=>true,
            \'query_var\' => true,
            \'show_in_menu \'=>true,
            \'show_in_nav_menus \'=>true,
            \'has_archive\' => \'works\',
            \'rewrite\' => array(\'slug\'=>\'work\',\'with_front\'=>false),
            \'menu_position\' => 2,
            \'menu_icon\' => get_stylesheet_directory_uri() . \'/library/images/custom-post-icon.png\',
            \'capability_type\' => \'post\',
            \'hierarchical\' => false,
            \'supports\'=>array(\'title\',\'editor\',\'thumbnail\',\'excerpt\'),
            \'taxonomies\'=>array(\'post_tag\')
        )
    ); 

1 个回复
最合适的回答,由SO网友:Pontus Abrahamsson 整理而成

把这个放在你的函数中。php:

function additional_active_item_classes($classes = array(), $menu_item = false){
    global $wp_query;

    if(in_array(\'current-menu-item\', $menu_item->classes)){
        $classes[] = \'current-menu-item\';
    }

    if ( $menu_item->post_name == \'product\' && is_post_type_archive(\'product\') ) {
        $classes[] = \'current-menu-item\';
    }

    if ( $menu_item->post_name == \'product\' && is_singular(\'product\') ) {
        $classes[] = \'current-menu-item\';
    }


    return $classes;
}
add_filter( \'nav_menu_css_class\', \'additional_active_item_classes\', 10, 2 );
此代码检查您是否在页面产品存档或单个产品上,如果是,则添加类当前菜单项

结束