0

Is it possible to have multiple custom post types appear on a category page?

For example, I have a category Animals and I can assign it to both these custom post types: dog, cat

Both cpts use a pre_get_posts filter:

function dog_query_post_type($query) {

    if( is_category() &&  $query->is_main_query() && empty( $query->query_vars['suppress_filters'] ) ) {
        $post_type = get_query_var('post_type');
        if($post_type)
            $post_type = $post_type;
        else
            $post_type = array( 'post', 'dog', 'nav_menu_item');

        $query->set('post_type',$post_type);

        return $query;
    }

}
add_filter('pre_get_posts', 'dog_query_post_type');

But only one cpt will appear on the Animals category page.

If I deactivate the plugin for the dogs cpt, then any cat cpts assigned to Animals will appear on the category page.

I have tried changing the priority settings on the add_filter calls.

And none of this affects the display of normal posts in the category from appearing on the category page.

I'd like to have any post, of any type, appear on the Animals page.

What am I missing?

2
  • Whatever filter runs last is going to overwrite whatever ran before it, as you're not adding to post types already set by previous filters, you are replacing it entirely with a different value.
    – Milo
    Dec 5, 2018 at 17:07
  • So obvious I couldn't see it. Thx.
    – shanebp
    Dec 5, 2018 at 18:34

1 Answer 1

2

Add to $post_type array, don't replace it...

function dog_query_post_type($query) {

    if( is_category() &&  $query->is_main_query() && empty( $query->query_vars['suppress_filters'] ) ) {
        $post_type = get_query_var('post_type');
        if($post_type)
            $post_type[] = 'dog';
        else
            $post_type = array( 'post', 'dog', 'nav_menu_item');

        $query->set('post_type',$post_type);

        return $query;
    }

}
add_filter('pre_get_posts', 'dog_query_post_type');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.