Tell me more ×
WordPress Answers is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

need some help for a special custom query.

I'm trying to build a single query to retrieve some posts from different categories instead of running several loop.

Is there a clean way to do that?

I have 3 categories (catA, catB and catC)

and I retrieve one random post per each category using three queries like this one:

//
// Loop A
//
function loop_A(){ 

    // The In Production Shows Query
    $args = array(
            'posts_per_page'  => 1,
            'category_name'   => 'catA',
            'orderby'         => 'rand',
            'post_status'     => 'publish' );

    $loop_A = new WP_Query( $args );

echo '<ul>';                
    // The Loop
    while ( $loop_A->have_posts() ) : $loop_A->the_post();
        ?>
        <li>
        <a href="<?php echo the_permalink(); ?>" title="<?php echo the_title_attribute(); ?>">
        <?php echo the_title(); ?>
        </a>
        </li>                   

    <?php
    endwhile;
echo '</ul>';

// Reset Post Data
wp_reset_postdata();            
    }

I probably have to add five categories in my page, so I'm trying to figure out how to avoid eight different queries running on a single page.

Hope some of you can help! I really appreciate every suggestion!

Thanks Bye Carletto

share|improve this question
You could have a look [here][1] [1]: wordpress.stackexchange.com/questions/907/… – ptriek Dec 3 '11 at 12:58

closed as too localized by toscho Feb 18 at 23:50

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, see the FAQ.

1 Answer

Haven't tested the code, but I think you could accomplish what you're trying to do with a few foreach loops:

<?php
$categories = get_categories('include=1,2,5');
foreach($categories as $category) {
$posts = get_posts('showposts=1&post_status=publish&orderby=rand&cat='. $category->term_id);

foreach($posts as $post) {
setup_postdata($post);
?>
// loop code
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<?php
}

}
?>
share|improve this answer

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