tags:

views:

207

answers:

4

How do I go about retrieving all of the blogposts from my Wordpress blog via an external PHP script? Is this even possible? I have seen the API for creating a Wordpress plugin, but I'm not sure if that is relevant in this particular case. Any suggestions are greatly appreciated. Thank you.

A: 

Wordpress has a feed that your posts get published to by default. You can read the XML feed, and parse out the relevant data.

I've got a vanity site that I use to send clients to, and I also contribute occasionally to a blog. One of the things that my vanity site shows is a short list of links to the top 5 most recent posts from the blog. Here's the code I use to do it:

<ul>
<?php
    //slurp latest post from Wordpress' RSS feed, and cache them for short time.
    $posts = '';
    $cachefile = 'my-blog-cache-file.html';
    if (is_readable($cachefile) && filemtime($cachefile) > (time() - 1800)) {
        readfile($cachefile);
    }
    else {
        $doc = new DOMDocument();
        $doc->load('http://my.wordpress.blog/feed');
        $items = $doc->getElementsByTagName('item');
        foreach($items as $i)
        {
            if ($i->hasChildNodes()) {
                $title = $link = '';
                foreach($i->childNodes as $cn) {
                    if ($cn->nodeName == 'title') $title = $cn->nodeValue;
                    if ($cn->nodeName == 'link') $link = $cn->nodeValue;
                    if ($cn->nodeName == 'dc:creator') $author = $cn->nodeValue;
                }
                if ($title != '' && $link != '' && $author == 'my name') {
                    $posts .= '<li><a href="'.$link.'">'.$title.'</a></li>'."\n";
                }
            }
        }
        file_put_contents($cachefile,$posts);
        echo $posts;
    }
?>
</ul>

Feel free to use this code. You can examine the feed of your own blog and decide what elements you want to parse out. Generally your feed will be located at your blog's URL, with /feed tacked onto the end.

zombat
+1  A: 

Your external script can load the wordpress api with

include('blog/wp-load.php'); // change blog/ to your actual path

Then you can use get_posts or query_posts to get the posts you want.

Jorbin
A: 
DavidYell
A: 

You'll want to take a look at Magpie. It's a fairly straight-forward RSS client for PHP, which let's you subscribe to any feed and get the posts with just a few lines of code.

SaintSal