Display WordPress posts outside of WordPress
WordPress can make for a great CMS, but sometimes it’s not always feasible or practical to use it for your entire site. One common scenario is to use WordPress for a blog that runs along side a site built with a completely different technology. However, a problem arises in this situation: What if you want to display blog posts on your non-WordPress site?
For example let’s, consider the following assumptions:
- You have a website built upon some sort of PHP stack. E.g CodeIgiter, CakePHP, Zend, whatever… It doesn’t really matter as long as it’s some sort of PHP website.
- You have a WordPress Blog in a separate /blog subdirectory of your website
- You want to display blog posts from the WordPress on the non-wordpress portion of your website. Maybe a “latests posts” section on the site, or something along those lines.
So, then, how do you get WordPress posts to display on a non-WordPress website? Luckily, WordPress provides a relatively easy way to tap into it’s inner workings, so you can retrieve posts outside the context of a WordPress site and display them just about anywhere.
WordPress the CMS is built upon a collection of powerful core APIs. You can actually load the core APIs into any PHP application, just like any other library. To do so is quite simple, you need only include the file wp-load.php where ever you want to include the WP core API. So, assuming your blog is located in /home/user/www/blog, the single line below loads in the core WP API into your non-wordpress application.
//Load WP API
Once the wp-load.php file is loaded into your code, you have the extensive WP API at your finger tips. For instance, you can query the database for the posts you want, and display them where you’d like to on your site. The code below illustrates a simple example of instantiating a WP_Query object, and displaying the latest 10 posts.
//instantiate a WP_Query and get the latest 10 posts
$wp_query = new \WP_Query();
//Iterate through the returned posts. The starts the WP "Loop"
while ($wp_query->have_posts()) :
<h1><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h1>
<?php the_content(); ?>
<?php endwhile; ?>
This is just a simple example. Your actual implementation would, of course, depend on how you’re integrating WordPress into your site.