Craig McCoy

Programmer / Developer & Zombie Survivalist

PHP Code Get Most Recent Wordpress Post

Jan/2010 24

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)