Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question
    
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
add comment

1 Answer 1

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
endwhile;
share|improve this answer
    
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
show 1 more comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.