Six Questions


School Visits



WordPress outside of WordPress

I do a fair amount of WordPress work, and one of the issues that frequently comes up is how to show WordPress posts outside of WordPress. In most cases, it’s easy enough to use wp-blog-header and the query_posts function.

That looks something like this:

query_posts( array ( 'category_name' => $catname, 'posts_per_page' => 5 ) );   
echo '<hr /><h2>Recent Stories from the Blog about '.$catname.'</h2>';   
while (have_posts()) :
    // use the_excerpt(),  the_permalink(), and the_title() to display the post,
    // or the "get_" variants to populate strings with them.

Easy, right? What about when the blog is on a subdirectory or a different server, somewhere that “require_once” won’t reach? That’s when we have to go the RSS route:

  $feed = simplexml_load_file('http://stories.daddytales.com/?feed=rss2'); 
  if ($feed) {     
 }  else {
   // do something because it couldn't get the feed.

The above code only illustrates getting the text items for the first item of the list. To show the text items, use a foreach loop. Here’s an example:

 $feed = simplexml_load_file('http://stories.daddytales.com/?feed=rss2');
 if ($feed) {  
  echo '<ul>';     
  foreach ($feed->channel->item as $feeditem) {
   echo '<li><a href="'.$feeditem->link.'">'.$feeditem->title.'</a><br />'.$feeditem->description.'</li>';
  } // end foreach loop
  echo '</ul>';

As of this writing, you have to use the rss2 feed, because it’s the one that has a date, and I usually like to show the dates for posts. The downside of this approach is that it’s hitting the server a second time, which is never good. But for cases where you can’t get to the wordpress files directly, it certainly does the trick! Also, if you don’t control the source of the feed, you might want to filter the text coming from it with an htmlentities or htmlspecialchar, or something like that.

I hope this helps!

Want to comment? Post it on Twitter!

Posted June 2, 2012 in Techie