How to List Blog Posts from outside WordPress

On my website, I’ve got two kinds of page. One kind is like my home page: coded directly as HTML. These pages are static, in that they are files which never change unless I edit them. The other kind of page belongs to this blog. These pages are implemented in WordPress, and are dynamic. When your browser asks for a WordPress page, it sends a web address to my server. The server looks for a PHP script at that address and runs it, and the script decides what HTML to send there and then, based on the contents of WordPress’s database. A good example is the page at http://www.j-paine.org/blog/ which lists my blog posts. But what should I do if I want to list these posts outside WordPress, for example on my home page? There’s an answer at “How to display recent posts outside WordPress” by Paul Green.

It’s the same kind of problem that I solved in “How to Run PHP under WordPress with Justyn’s Magic Includer”. There, I needed to stand outside WordPress and run a script that added information to its database about the names and times and venues of a teacher’s classes, so that they could be displayed by the Promenade theme. Here, I need to stand outside it and run a script that loops through the database returning the text of each and every blog post. In both cases, the scripts need to know where to find the WordPress functions they must call to do the job. In terms of the analogy I used in my Justyn’s Magic Includer post, I need to tell my scripts that to find the WordPress tools, they’ll have to rummage around behind that pile of motorbike spares at the back of my garage.

Here’s a demonstration. The script is below, a shortened version of the one in Paul Green’s post, and also similar to the “Standard Loop” examples in “Class Reference/WP Query” from the authoritative WordPress Codex. You can see what its output looks like by going to http://www.j-paine.org/blog/demos/posts_demo.php.

<?php

/* posts_demo.php */

/*
A simple script that demonstrates
looping through blog posts and
displaying each one.
*/

require( $_SERVER['DOCUMENT_ROOT'] . '/blog/wp-load.php' ); 

$args = array( 'posts_per_page' => -1 );
$latest_posts = new WP_Query( $args ); 	

while ( $latest_posts->have_posts() ) {
  $latest_posts->the_post(); 
  the_title(); 
  echo "<BR>\n";
  the_time( 'l jS F, Y' ); 
  echo "<BR>\n";
  the_excerpt(); 
  echo "<BR><BR>\n";
}

wp_reset_postdata();

?>

(Continued.)

Leave a Reply

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