Get Recent Posts In WordPress In A New Way

 Get Recent Posts In WordPress In A New Way

Getting recent posts is an easy and must-have work in every WordPress blog. You’ve seen many ways to do that, such as using plugin, widget, query_posts() function or even custom code to directly access database. But do you know that WordPress has already a built-in function for this?

The function is wp_get_recent_posts(), it has one parameter, that is the number of most recent posts. By default wp_get_recent_posts() retrieves 10 most recent posts.

<?php wp_get_recent_posts( $num ) ?>

To show most recent posts in your theme, you just use the following code:

<h2>Recent Posts</h2>
<ul>
<?php
    $recent_posts = wp_get_recent_posts(5);
    foreach($recent_posts as $post){
        echo '<li><a href="'.get_permalink($post["ID"]).'" title="'.$post["post_title"].'" >'.$post["post_title"].'</a></li>';
    }
?>
</ul>

Using the built-in function of WordPress give us the safety. We don’t have to care how to access database to get recent posts (if we use custom code), or the long list of parameters (in case of using query_posts). WordPress does it all for us.

1 Comment

Leave a Reply