Display the most recent articles with WP_Query, but exclude the latest article

To display the latest articles with WP_Query in WordPress but exclude the most recent article, you can use the following code:

<?php
$args = array(
    'post_type'      => 'post',
    'posts_per_page' => 5,
    'post_status'    => 'publish',
    'offset'         => 1 // Exclude the latest article
);

$query = new WP_Query( $args );

if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();
        // Display the article content
        ?>
        <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
        <p><?php the_excerpt(); ?></p>
        <?php
    }
} else {
    // No posts found
}

// Restore original post data
wp_reset_postdata();
?>

In this code, we define the $args array with the necessary parameters for the WP_Query object. The post_type is set to 'post' to retrieve regular blog posts. The posts_per_page parameter specifies the number of posts to display, and the post_status is set to 'publish' to fetch only published articles.

To exclude the latest article, we use the offset parameter and set it to 1, which skips the first post. Adjust this value if you want to exclude a different number of posts.

The code then checks if there are any posts returned by the query using the have_posts() method. Inside the loop, we can access the post data using WordPress template tags such as the_title(), the_permalink(), and the_excerpt() to display the article’s title, permalink, and excerpt, respectively.

After the loop, we use wp_reset_postdata() to restore the global post data to its original state.

Feel free to modify the code according to your specific requirements or integrate it into your WordPress theme or plugin.

Member since January 2, 2019

As a seasoned WordPress developer with expertise in various tech stacks and languages, I bring years of experience to every project I handle. My passion for coding and dedication to delivering exceptional work ensures that each project I take on is of the highest quality. I specialize in creating custom themes, developing plugins, and building full-scale web systems. By staying up-to-date with the latest industry trends and best practices, I incorporate cutting-edge solutions into my work.

Comments

  • Ben J 1 year ago

    Ohh! Nice! I was stuck on this for hours. Your tutorial just saved my day. Keep it up!

Your email address will not be published. Required fields are marked *