简体   繁体   中英

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. 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? Thank you.

Managed to solve the problem by adding this snippet to my 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' );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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