如何从外部脚本中检索博客帖子(Wordpress)

时间:2009-12-30 03:08:52

标签: php wordpress

如何通过外部PHP脚本从我的Wordpress博客中检索所有博客帖子?这甚至可能吗?我已经看到了用于创建Wordpress插件的API,但我不确定这是否与此特定情况相关。任何建议都非常感谢。谢谢。

4 个答案:

答案 0 :(得分:1)

您的外部脚本可以使用

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

然后你可以使用get_posts或query_posts来获得你想要的帖子。

答案 1 :(得分:0)

Wordpress有一个您的帖子默认发布到的Feed。您可以阅读XML提要,并解析相关数据。

我有一个我用它来发送客户的虚荣网站,我偶尔也会为博客做贡献。我的虚荣网站显示的一件事是一个简短的链接列表,列出了博客最近的5篇最新帖子。这是我用来做的代码:

<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>

随意使用此代码。您可以检查自己博客的供稿,并确定要解析的元素。通常,您的Feed会位于您博客的网址上,最后会加/feed

答案 2 :(得分:0)

另一种选择当然是使用PHP连接到您的数据库并自己读取数据库:)

//You'll want to set your database credentials 
mysql_connect($server, $username, $password);
mysql_select_db($wp_db);

// Modify the fields to pull whatever data you need for the output, even perhaps join the wp_users table for user data // Setting the ORDER BY to DESC to mimic the Wordpress ordering with newest first $sql = "SELECT ID, post_author, post_date, post_content, post_title, post_status, post_name, guid FROM wp_posts ORDER BY post_date DESC"; $data = mysql_query($sql);

$num = count($data); for($i = 0; $i < $num; $i++){ $row = mysql_fetch_array($data); // Output your posts to something print_r($row); }

这样可以让您更轻松地使用数据:)

答案 3 :(得分:0)

您需要查看Magpie。这是一个非常直接的PHP RSS客户端,让你订阅任何一个feed并只用几行代码来获取帖子。

相关问题