获取WordPress最新文章列表

获取WordPress的最新文章列表虽然很容易,但似乎并不太满足我的要求。最简单的获取方法只需要两行代码就可以搞定,如下:

<?php require('wp-blog-header.php'); ?>
<?php get_archives('postbypost', 10); ?>

但我的想法是,获取最新文章列表,然后输出到html文件,最后在需要的地方直接调用这个html文件即可。但上面两行似乎是直接输出,而不能将输出的内容直接保存成文件,于是乎Google了一下又找了一段,简单修改了下,算是满足我的需求了。如下:

<?php
//调用WP的配置文件,别小看这个文件哦,这里改成你的blog的路径.
require_once('wp-config.php');
//这个函数从中文工具箱中copy的
//调用wp-config.php文件的目的主要是使用他的db查询功能,可以自己写连接MYSQL部份,但是觉得没有必要.
//主要应用在$wpdb变量中
function get_recent_posts($no_posts = 5, $before = '<li>', $after = '</li>', $show_pass_post = false, $skip_posts = 0) {
    global $wpdb, $tableposts;
    $request = "SELECT ID, post_title, post_date, post_content FROM $wpdb->posts WHERE post_status = 'publish' ";
        if(!$show_pass_post) { $request .= "AND post_password ='' "; }
    $request .= "ORDER BY post_date DESC LIMIT $skip_posts, $no_posts";
    $posts = $wpdb->get_results($request);
    $output = '';
    foreach ($posts as $post) {
        $post_title = stripslashes($post->post_title);
//         $post_date = mysql2date('j.m.Y', $post->post_date);
        $permalink = get_permalink($post->ID);
        $output .= $before . '<a href="' . $permalink . '" rel="bookmark" title="Permanent Link: ' . $post_title . '">' . $post_title . '</a>'. $after;
    }
    return $output;
}

function mul_excerpt ($excerpt) {
     $myexcerpt = substr($excerpt,0,255);
     return utf8_trim($myexcerpt) . '... ';
}

//执行函数,输出结果,这里你可以去掉下面这行,通过包含本文件来调用get_recent_comments();函数。
//get_recent_posts();

$content = get_recent_posts();
echo $content;
$countfile="recentposts.html";  //生成一个recentposts文件
if(!file_exists($countfile)) 

    fopen($countfile,"w"); //如果此文件不存在,则自动建立一个 

$fp=fopen($countfile,"r"); 
$fp=fopen($countfile,"w"); 
fwrite($fp,$content); //更新其值 
fclose($fp); 
?>
更新完毕,返回<a href="index.php">首页</a>

上面的代码就是生成文章列表,并实现输出到recentposts.html文件,将上面的代码保存成getrecentposts.php文件即可。调用时直接用这个html文件就可以了,如下:

<?php include('recentposts.html'); ?>

至此,获取WordPress最新文章列表算是完毕了,但需要每次发表文章后需要访问getrecentposts.php以更新html文件。

好了,你也试试看吧。

RoverTang@罗孚传说
E-mail:65985498[at]qq.com
微博/微信:rovertang

原文地址:https://www.cnblogs.com/Tangf/p/2221202.html