Adding your latest WordPress blog posts to a non-WordPress page

When I looked into adding the latest posts from my WordPress blog to my non-WordPress home page, I found out it was much easier than I thought. The solution thankfully doesn’t involve iframes or complicated PHP code. Although you at least need to be familiar with PHP and WordPress’ built-in functions.

Since the page you want to add your latest posts is outside of your WordPress installation, you need to access WordPress’ functionality or as some refer to it as ‘hooking into WordPress’. These procedures are only for sites where WordPress is installed for just part of the site, say for example you had WordPress installed in a subfolder named ‘blog’. First you want to add this PHP code near the top of the page:

<?php define('WP_USE_THEMES', false);

The above code loads WordPress functionality into the page and retrieves the last four blog posts. A quick explaination on what each line of code does. The first line sets the PHP constant ‘WP_USE_THEMES’ to false. This stops the header of the active WordPress theme from loading. The second line loads the wp-load PHP file, which contains WordPress’ core functionality. The query_posts function on the third line is a built-in WordPress PHP function that contains for a parameter a query of the last four posts.

Now code needs to be added to display the blog posts on the page. It’s really just a PHP while function. I’ll use the code on my homepage as an example:

<div id="blogpreview" class="small-12 columns">
<?php while (have_posts()): the_post(); ?>
<h4><?php the_title(); ?></h4>
<?php the_excerpt(); ?>
<p><a target="_blank" href="<?php the_permalink(); ?>">Read more...</a></p>
<?php endwhile; ?>

Given WordPress has been loaded onto the page, all of the WordPress built-in functions can now be accessed. This makes the amount of code having to be written to access information about each blog post much smaller. The ‘while(have_posts()): the_posts();’ checks if there are posts present and then loops through the four posts queried in the previous PHP code. The built-in WordPress functions like ‘the_title()’, ‘the_excerpt()’, and ‘the_permalink()’ display the corresponding info about each blog post. There many more functions available that can be used to add even more information about each post, such as ‘the_category()’, ‘the_tags()’, and ‘the_author()’.

What I like most about this solution is the flexibility it provides with layout and styling. The PHP while function should be in some kind of block level element. I used a div element, however an unordered list or even a table could be used. The number of posts retrieve is entirely up to you. To change the number of posts, just modify the number in the query_posts function: query_posts(‘showposts=4’);.

Matthew Dailey

Web developer, photographer, and Photoshop user.