First post of each category

It’s not possible to get one posts per category with one simple query, and even a complex query will take more time than 3 separate query. So, if you want simplest, then this is the solution –

$cats = array('lifestyle', 'fashion', 'beauty');
$exclude_posts = array();
foreach( $cats as $cat )
{
    // build query argument
    $query_args = array(
        'category_name' => $cat,
        'showposts' => 1,
        'post_type' => 'post',
        'post_status' => 'publish',
        'orderby' => 'date',
        'order' => 'DESC'
    );

    // exclude post that already have been fetched
    // this would be useful if multiple category is assigned for same post
    if( !empty($exclude_posts) )
        $query_args['post__not_in'] = $exclude_posts;

    // do query
    $query = new WP_Query( $query_args );

    // check if query have any post
    if ( $query->have_posts() ) {

        // start loop
        while ( $query->have_posts() ) {
            // set post global
            $query->the_post();

            // add current post id to exclusion array
            $exclude_posts[] = get_the_ID();


            // do something
        }
    } else {
        // no posts found
    }

    // Restore original Post Data
    wp_reset_postdata();
}

Leave a Comment