Getting Recent Posts Outside Of WordPress

Many sites do use WordPress for blogging but they do not use it as back-end for whole site. (Your site or app may be one of them.) There may be a scenario in which you have to display recent posts from WordPress blog, on a page which is outside of WordPress. No problem. You might know that WordPress is quite flexible, hence you can handle such scenario with a small code. There are two ways to achieve this. You can either take advantage of WordPress loop itself or if you don’t want to deal with WordPress loop then you can use other way also.

If you don’t want WordPress loop

So you don’to want to take advantage of WordPress loop? Then you can use wp_get_recent_posts(). According to WordPress codex:

wp_get_recent_posts() will return a list of posts. Different from get_posts which returns an array of post objects.

How to use it?

Just copy paste following code in page where you want to list the Recent Posts

include('wp-load.php');

// Get the last 10 posts
$recent_posts = wp_get_recent_posts(array(
  'numberposts' => 10,
  'post_type' => 'post',
  'post_status' => 'publish'
));
  
// Display them as list
echo '<ul>';
foreach($recent_posts as $post) {
  echo '<li><a href="', get_permalink($post['ID']), '">', $post['post_title'], '</a></li>';
}
echo '</ul>';

You can simply change numberposts parameters value to change the number of posts you want to retrieve.

If you want to take advantage of WordPress loop

So if you want to take advantage of awesome WordPress loop then you can use following code to retrieve posts from WordPress blog.

define('WP_USE_THEMES', false);
include('blog/wp-load.php');
//Get posts
query_posts('showposts=5');

// Display them as list
echo '<ul>';
foreach($recent_posts as $post) {
  echo '<li><a href="', the_permalink(), '">', the_title(), '</a></li>';
}
echo '</ul>';

In both cases you might have noticed that we are using wp-load.php to get connected with WordPress installation. Once that file is included all WordPress functionality will be available to you. That means you can interact in any way as you wish with your WordPress installation.

Note:
Since wp-load.php is included in your page which is outside of WordPress, you may face error with some of WordPress plugins and cache. To turn off cache for that page on which you just want to show posts you can add define('WP_CACHE', FALSE); just after include('blog/wp-load.php');.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.