how do i get only 1 post from each category in wordpress

sonill picture sonill · Jul 16, 2010 · Viewed 9.7k times · Source

i have a category named news and many subcategories inside it. What i wanna do is to get only 1 posts(newest) from each of those sub categories(including category title, post title, attachment image). Is there any suggestions friends??

Answer

TheDeadMedic picture TheDeadMedic · Jul 17, 2010
<?php

$news_cat_ID = get_cat_ID( 'News' ); 
$news_cats   = get_categories( "parent=$news_cat_ID" );
$news_query  = new WP_Query;

foreach ( $news_cats as $news_cat ) :
    $news_query->query( array(
        'cat'                 => $news_cat->term_id,
        'posts_per_page'      => 1,
        'no_found_rows'       => true,
        'ignore_sticky_posts' => true,
    ));

    ?>

    <h2><?php echo esc_html( $news_cat->name ) ?></h2>

    <?php while ( $news_query->have_posts() ) : $news_query->the_post() ?>

            <div class="post">
                <?php the_title() ?>
                <!-- do whatever you else you want that you can do in a normal loop -->
            </div>  

    <?php endwhile ?>

<?php endforeach ?>