从自定义帖子类型类别列出帖子?

时间:2015-07-13 10:20:13

标签: php wordpress custom-post-type

我有一个自定义的帖子类型和一个像这样创建的组合分类:

    $args = array(
        'label' => __('Portfolio', 'my-portfolio'),
        'labels' => array(
            'add_new_item' => __('New portfolio', 'my-portfolio'),
            'new_item' => __('New portfolio', 'my-portfolio'),
            'not_found' => __('No portfolio items', 'my-portfolio'),
        ),
        'singular_label' => __('Portfolio', 'my-portfolio'),
        'menu_icon' => 'dashicons-portfolio',
        'public' => true,
        'show_ui' => true,
        'capability_type' => 'post',
        'hierarchical' => true,
        'has_archive' => true,
        'exclude_from_search' => true,
        'show_in_nav_menus' => false,
        'supports' => array('title', 'editor', 'thumbnail'),
        'rewrite' => array('slug' => 'portfolio', 'with_front' => false),
        'register_meta_box_cb' => 'add_remove_metaboxes_portfolio',
       );

    //Register type and custom taxonomy for type.
    register_post_type( 'portfolio' , $args );
    register_taxonomy("portfolio-category", array("portfolio"), array("hierarchical" => true, "label" => "Categories", "singular_label" => "Category", "rewrite" => true, "slug" => 'portfolio-category',"show_in_nav_menus"=>false));

当我在查询中使用它时,它会像它应该的那样工作。它显示在后端的菜单中,以及此自定义帖子类型的类别。

我的问题是,当我尝试从某个类别检索所有帖子时(通过点击类别名称),我在页面上显示No posts were found. Sorry!

该页面是一个默认的wordpress存档,应该只列出所有帖子,但没有显示任何内容。网址是这样的:

http://xampp/my-theme/?portfolio-category=animals

但即使我使用后名永久链接也无效。

我已阅读CSS Tricks我可以在functions.php

中使用此功能
function namespace_add_custom_types( $query ) {
  if( is_category() || is_tag() && empty( $query->query_vars['suppress_filters'] ) ) {
    $query->set( 'post_type', array(
     'post', 'portfolio', 'nav_menu_item'
        ));
      return $query;
    }
}
add_filter( 'pre_get_posts', 'namespace_add_custom_types' );

但这也无济于事。我在这里缺少什么?

1 个答案:

答案 0 :(得分:0)

您必须为自定义帖子类型使用存档页面模板。请将代码放入自定义帖子类型

$args = array(
        'label' => __('Portfolio', 'my-portfolio'),
        'labels' => array(
            'add_new_item' => __('New portfolio', 'my-portfolio'),
            'new_item' => __('New portfolio', 'my-portfolio'),
            'not_found' => __('No portfolio items', 'my-portfolio'),
        ),
        'singular_label' => __('Portfolio', 'my-portfolio'),
        'menu_icon' => 'dashicons-portfolio',
        'public' => true,
        'show_ui' => true,
        'capability_type' => 'post',
        'hierarchical' => true,
        'has_archive' => true,
        'exclude_from_search' => true,
        'show_in_nav_menus' => false,
        'supports' => array('title', 'editor', 'thumbnail'),
        'rewrite' => array('slug' => 'portfolio', 'with_front' => false),
        'register_meta_box_cb' => 'add_remove_metaboxes_portfolio',
       );

    //Register type and custom taxonomy for type.
    register_post_type( 'portfolio' , $args );
flush_rewrite_rules();