First post of each category

I’m trying to create a simple loop, that gets the latest post of 3 selected categories. I’ve searched for something similar to learn from, but most are overly complex.

At the moment, I have:

Read More
    <?php 

    // WP_Query arguments
$args = array (
    'category_name'          => array('lifestyle', 'fashion', 'beauty')
);

// The Query
$query = new WP_Query( $args[0] );

// The Loop
if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();
        // do something
    }
} else {
    // no posts found
}

// Restore original Post Data
wp_reset_postdata();

?>

I assume I’d need a foreach loop, but I’m unsure how to implement it in this scenario, and for just the latest of each post?

Any help would be great.

Related posts

1 comment

  1. 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();
    }
    

Comments are closed.