How to use WordPress get Recent Posts in PHP?

The most appropriate use for get_posts is to create an array of posts based on a set of parameters. It retrieves a list of recent posts or posts matching this criteria. get_posts can also be used to create Multiple Loops, though a more direct reference to WP_Query using new WP_Query is preferred in this case.

<?php
// Define the query parameters
$args = array(
    'numberposts' => 5,          // Number of posts to fetch
    'post_type'   => 'post',     // Fetch only posts
    'orderby'     => 'date',     // Order by date
    'order'       => 'DESC'      // Descending order (most recent first)
);

// Fetch posts
$recent_posts = get_posts($args);

// Check if there are posts
if (!empty($recent_posts)) :
    foreach ($recent_posts as $post) : setup_postdata($post); ?>
        <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
        <p><?php the_excerpt(); ?></p>
    <?php endforeach;

    // Reset post data to default query
    wp_reset_postdata();
else :
    echo '<p>No recent posts found.</p>';
endif;
?>

If you want to show post in category wise to add this one line code.

'category'      => 1              // Replace with the category ID or slug
$args = array(
    'post_type'      => 'post',       // Fetch only posts
    'posts_per_page' => 5,            // Number of posts to fetch
    'orderby'       => 'date',        // Order by date
    'order'         => 'DESC',        // Descending order (most recent first)
    'category'      => 1              // Replace with the category ID or slug
);

If you want to know how to get category id, click the link

administrator

Leave a Reply

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