PHP Code Get Most Recent Wordpress Post

PHP Code Get Most Recent Wordpress Post

This is a quick example using only vanilla PHP.  There are more dynamic ways to do this using RSS classes built into PHP addons, which I won’t go into detail here.  Instead, we will just use vanilla PHP, and parse the XML by hand.

On to the code, I take 3 arguments here, number of posts to return, the RSS URL, and an optional max number of characters to return.

//get most recent rss
//get most recent rss
function recent_rss($display=0,$url='', $description_limit = 0) {
	$itemArr = array();
    $doc = new DOMDocument();
    $doc->load($url);
 
    foreach ($doc->getElementsByTagName('item') as $node) {
        if ($display == 0) {
            break;
        }
 
    $description = $node->getElementsByTagName('description')->item(0)->nodeValue;
 
    //if limit passed in, truncate string
    if($description_limit > 0) {
		$description = substr($description, 0, $description_limit)."..."; 	
	}
 
        $itemRSS = array (
            'title'       => $node->getElementsByTagName('title')->item(0)->nodeValue,
            'description' => $description,
            'link'        => $node->getElementsByTagName('link')->item(0)->nodeValue,
            'pubdate'     => $node->getElementsByTagName('pubDate')->item(0)->nodeValue
        );
 
         array_push($itemArr, $itemRSS);
 
        $display--;
    }
    return $itemArr;
}
 
//example use
$recent_post = recent_rss(1, 'http://houseplansblog.nelsondesigngroup.com/index.php/feed/', 0);
var_dump($recent_post);

Now, Here is a quick and dirty XHTML example showing how you might implement this on a page. (Note the use of the preg_replace to get rid of weird characters that get into the RSS sometimes)

<div id="rss_container" style="width:250px;">
 
	<div id="rss_title">
		<a href='<?php echo $recent_post[0]["link"]; ?>'>
			<?php echo  preg_replace('/[^(\x20-\x7F)]*/','', $recent_post[0]["title"]);?>
		</a>
	</div>
 
	<div id="rss_pub_date">
		<?php echo $recent_post[0]["pubdate"];?>
	</div>
 
	<div id="rss_description">
		<?php echo $recent_post[0]["description"];?>
	</div>
 
</div>

You Might Also Like...

  • Chad
    This code works great. I'm pretty sure it works for almost any blog, as it pulls out the info from your rss feed.
  • Does this work for every version of Wordpress?

    Would we have to worry about it no longer working when the next version is released?
blog comments powered by Disqus