WordPress教程

纯代码实现WordPress显示最近更新过的文章

阿里云

如题,创客云经常开发一些博客主题,有时客户要求在文章内容底部显示最近更新的文章,不是相关文章,而且我们有时候会因为一些功能的不完美或者代码的时效性、软件主题的更新等,对一些旧文章进行一些不定期更新,但是这种更新一旦没有及时通知访客,往往就没有什么意义了,访客很难知道。

1、代码部署

将以下代码添加到主题的 functions.php 里:

也想出现在这里?联系我们
创客主机
  1. function recently_updated_posts($num=10,$days=7) {  
  2.    if( !$recently_updated_posts = get_option('recently_updated_posts') ) {  
  3.        query_posts('post_status=publish&orderby=modified&posts_per_page=-1');  
  4.        $i=0;  
  5.        while ( have_posts() && $i<$num ) : the_post();  
  6.            if (current_time('timestamp') - get_the_time('U') > 60*60*24*$days) {  
  7.                $i++;  
  8.                $the_title_value=get_the_title();  
  9.                $recently_updated_posts.='<li><a href="'.get_permalink().'" title="'.$the_title_value.'">'  
  10.                .$the_title_value.'</a><span class="updatetime"><br />&raquo; 修改时间: '  
  11.                .get_the_modified_time('Y.m.d G:i').'</span></li>';  
  12.            }  
  13.        endwhile;  
  14.        wp_reset_query();  
  15.        if ( !empty($recently_updated_posts) ) update_option('recently_updated_posts', $recently_updated_posts);  
  16.    }  
  17.    $recently_updated_posts=($recently_updated_posts == '') ? '<li>None data.</li>' : $recently_updated_posts;  
  18.    echo $recently_updated_posts;  
  19. }  
  20.  
  21. function clear_cache_zww() {  
  22.     update_option('recently_updated_posts', ''); // 清空 recently_updated_posts  
  23. }  
  24. add_action('save_post', 'clear_cache_zww'); // 新发表文章/修改文章时触发更新

2、调用方法

  1. <h3>Recently Updated Posts</h3>  
  2. <ul>  
  3. <?php if ( function_exists('recently_updated_posts') ) recently_updated_posts(8,15); ?>  
  4. </ul>

其中 8 为展示文章数量,15 指 15 天内发表的文章除外,具体使用的时候可以根据自己的情况修改这两个参数。作者有添加数据库缓存方式,所以在修改文章/删除文章/发表文章时才会更新缓存。
相关参数说明:$num - 展示数量,$days - 几天内的新文章除外。

纯代码实现 WordPress 显示最近更新过的文章

已有 339 人购买
查看演示升级 VIP立刻购买

收藏
(0)

发表回复

热销模板

Ashade - 作品展示摄影相册WordPress汉化主题
LensNews

本站承接 WordPress / PbootCMS / DedeCMS 等
系统建站、仿站、开发、定制等业务!