questions

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

Rate this post

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:

You can create shortcode that you can put in any widget area you want. Something like:

function wpb_rand_posts() { 
 
 
if ( $the_query->have_posts() ) {
 
$string .= '<ul>';
    while ( $the_query->have_posts() ) {
       //do stuff
    }
    $string .= '</ul>';
    /* Restore original Post Data */
    wp_reset_postdata();
} else {
 
$string .= 'no posts found';
}
 
return $string; 
} 
 
add_shortcode('wpb-random-posts','wpb_rand_posts');
add_filter('widget_text', 'do_shortcode'); 

Leave a Reply

Your email address will not be published.

Back to top button