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>

A Letter to Windows 7

windows-7-logo

Dear Windows 7,

First, I want to thank you for confirming my hatred for all things that slink out of Redmond, Washington, you have my gratitude. For a few hours there, I really thought I was going to bury the hatched with Microsoft, but then you showed me the truth and for that, I owe you one.
Read More »

Ryan Seacrest is Hot!

image_3l