Search code examples
wordpresscustom-post-type

How to display a custom post type feed in the sidebar of a category page?


I have a custom post type setup and in the sidebar of every page on the site it is set to display a random post from that custom post type (named "reviews").

This works great everywhere except for category pages for the normal / standard / default post type of "post" where even though the query is setup to only use the custom post type "reviews" it only pulls from the default blog posts.

Is there something I am leaving out to make sure this works even on category pages?

Here is the code I am using that works fine on non category pages, you can see it is restricted to just the "reviews" post type:

// the query
                    $review_query = new WP_Query( array (
                        'post_type' => 'reviews', // Display just this post type
                        'orderby'        => 'rand',
                        'posts_per_page' => 1,
                    )
                );

Solution

  • Ok so it turns out the code I had added to functions.php to make sure a different custom post type was displaying in the category feed was interfering.

    So this was the original code snip I used to do that:

        // Show notable cases in tag archives
    function themeprefix_show_cpt_archives( $query ) {
     if( is_category() || is_tag() && empty( $query->query_vars['suppress_filters'] ) ) {
     $query->set( 'post_type', array(
     'nav_menu_item', 'post', 'cases'
     ));
     return $query;
     }
    }
    

    And I changed that to this:

    // Show notable cases in tag archives
    function themeprefix_show_cpt_archives( $query ) {
    if( empty( $query->query_vars['suppress_filters'] ) && ( is_category() || is_tag() )   ) {
    $query->set( 'post_type', array(
    'nav_menu_item', 'post', 'cases'
    ));
    return $query;
    }
    }
    

    And added suppress_filters' => true to my query, and this resolved my issue. If anyone else runs into this see what else in your theme may be modifying the query at a higher level through a function like this or plugin as this is a solution specific to the code in my theme.