Display one latest post from multiple categories

What about in_category() function? You can build a conditional for those categories and then use a $var to show just one post, filtering previously those cats on the query. It would be something like that:

<?php query_posts( 'posts_per_page=-1&cat=1,2,3,4,5,6' ); $var = 0; ?>

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

    <?php if ( in_category(1) && $var == 0 ) : ?>

        //Title, links etc comes here....
        <?php $var++; ?>

    <?php elseif ( in_category(2) && $var == 1 ): ?>

        //Title, links etc comes here....
        <?php $var++; ?>

    <?php elseif ( in_category(3) && $var == 2 ): ?>

        //Title, links etc comes here....
        <?php $var++; ?>

    <?php elseif ( in_category(4) && $var == 3 ): ?>

        //Title, links etc comes here....
        <?php $var++; ?>

    <?php elseif ( in_category(5) && $var == 4 ): ?>

        //Title, links etc comes here....
        <?php $var++; ?>

    <?php elseif ( in_category(6) && $var == 5 ): ?>

        //Title, links etc comes here....
        <?php $var++; ?>

    <?php endif; ?>

<?php endwhile; endif; ?>

<?php wp_reset_query(); ?>

You need to call all the post with posts_per_page=-1, but I still think that 1 query is better than 6. I know that is not the best option, but it works… I’m working to get a simpler code. Hope it helps.

Leave a Comment