简体   繁体   English

显示自定义帖子类型类别存档页面

[英]Displaying custom post type category archive page

I have created custom post type:我创建了自定义帖子类型:

function create_posttype() {

register_post_type( 'builds',
// CPT Options
    array(
        'labels' => array(
            'name' => __( 'Builds' ),
            'singular_name' => __( 'Build' )
        ),
                'taxonomies' => array('category', 'post_tag'),
        'public' => true,
        'has_archive' => true,
        'rewrite' => array('slug' => 'builds'),
                    'supports' => array('thumbnail', 'title', 'excerpt',      'revisions', 'comments', 'author')
    )
);}

       // Hooking up our function to theme setup
     add_action( 'init', 'create_posttype' );`

Custom post type is working without any problems but I cannot get one thing to work:自定义帖子类型可以正常工作,但我无法完成一件事:

So basic idea is that there is custom post type "Builds" and I am using post categories (not custom taxonomies, because in my situation it's not viable option) to separate these Builds - for example Melee builds, Ranged builds, Spell Builds etc. I'd like to make archive for each category of custom post type, for example display all the Melee builds.所以基本的想法是有自定义帖子类型“构建”并且我使用帖子类别(不是自定义分类法,因为在我的情况下它不是可行的选项)来分离这些构建 - 例如近战构建,远程构建,法术构建等。我想为每个类别的自定义帖子类型制作存档,例如显示所有近战版本。 For that I am using category templates, for example category-melee.php based on category slug which is working fine, but it doesn't show any posts from custom post type there - only regular posts with given category.为此,我正在使用类别模板,例如基于类别 slug 的category-melee.php ,它工作正常,但它没有显示来自自定义帖子类型的任何帖子 - 只有具有给定类别的常规帖子。 What to do in this situation?在这种情况下该怎么办? Should I try to find and modify wp_query somewhere in theme to include "Builds" (because I've tried that and without success) or are there some other workarounds?我应该尝试在主题中的某处查找和修改wp_query以包含“构建”(因为我已经尝试过但没有成功)还是有其他一些解决方法? Thank you.谢谢你。

Managed to solve the problem by adding this snippet to my functions.php设法通过将此代码段添加到我的functions.php来解决问题

add_action('pre_get_posts', function($query) {
if ( ! is_admin() && $query->is_main_query() ) {

    if ( is_archive() || is_category() ) {
        $query->set( 'post_type', 'builds' );
    }


}
});
function namespace_add_custom_types( $query ) 
{
   if( is_category() || is_tag() && empty( $query->query_vars['suppress_filters'] ) ) 
   {
      $query->set( 'post_type', array(
      'post', 'nav_menu_item', 'your-custom-post-type-here'
       ));
      return $query;
   }
}
add_filter( 'pre_get_posts', 'namespace_add_custom_types' );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM