i have this line.. in sidebar..

<?php query_posts ( ( array('orderby' => 'rand', 'showposts' => 12)));?>

i want to order by category not random.. so if i am in a post from category animals.. i want to show 12 post just from this category. Not Random like now..

how can i do that?

  • Do you have one category per post? If you can have multiple categories per post how would you expect posts that have multiple categories to be displayed? – MikeSchinkel Jan 1 '11 at 21:20

This should limit the posts pulled in the new WP_Query instance to the currently selected category or the first category of the current post.

global $wp_query;
$sidebar_query_vars = array('orderby' => 'rand', 'showposts' => 12);
if(is_category()) {
    $sidebar_query_vars['cat'] = $wp_query->get_queried_object()->term_id;
} elseif (is_single()) {
    $categories = (get_the_terms($wp_query->get_queried_object_id(), 'category'));
    if(is_array($categories)) {
        $first_cat = array_shift($categories);
        $sidebar_query_vars['cat'] = $first_cat->term_id;
$sidebar_query = new WP_Query($sidebar_query_vars);
while($sidebar_query->have_posts()): $sidebar_query->the_post();
//do output here
  • Last line should read: ‘$sidebar_query = new WP_Query($sidebar_query_vars);‘, right? – goldenapples Jan 2 '11 at 6:38
  • is not working..it shows me just 1 post and is the same post i am in.. – Joshmax23 Jan 2 '11 at 9:43
  • I updated the code to include the loop. That was missing from my previous answer. – prettyboymp Jan 2 '11 at 21:53
  • i replace this line < ? php query_posts ( ( array('orderby' => 'rand', 'showposts' => 12)));?> with your code.. and still show me just 1 post and is same post i am in.. i do something wrong? Thanks. – Joshmax23 Jan 3 '11 at 9:48
  • @Joshmax23: Your original code uses query_posts(), which sets the "normal" $wp_query variable to hold the loop. This answer uses $sidebar_query, so you should adapt your loop to also start with while ( $sidebar_query->have_posts() ) ... like in the answer. – Jan Fabry Jan 3 '11 at 18:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy