·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> 网站建设问答 >> 最新、热评、随机日志函数三体合一

最新、热评、随机日志函数三体合一

作者:佚名      网站建设问答编辑:admin      更新时间:2022-07-23

最新日志、热评日志、随机日志这三个功能在函数上是很相近的,无非就是一个排序的不同,最新日志是按照发布时间排序,热评日志是按照评论数量排序,随机日志则是随机排序。所以我索性就把这三个函数合并为一,一方面减少 functions.php 中代码的冗余,另一方面也方便自己管理。

把以下函数复制到 WordPress 主题目录下的 functions.php 中:

function get_posts($orderby = '', $plusmsg = '') {
    $get_posts = query_posts('posts_per_page=10&caller_get_posts=1&orderby='.$orderby);
    foreach ($get_posts as $get_post) {
            $output = '';
            $post_date = mysql2date('y年m月d日', $get_post->post_date);
            $commentcount = '('.$get_post->comment_count.' 条评论)';
            $post_title = htmlspecialchars(stripslashes($get_post->post_title));
            $permalink = get_permalink($get_post->ID);
            $output .= '<li><a href="' . $permalink . '" title="'.$post_title.'">' . $post_title . '</a>'.$$plusmsg.'</li>';
            echo '<ul>'.$output.'</ul>';
        }
    wp_reset_query();
}

调用方法分别如下:

<?php
//最新日志
get_posts( $orderby = 'date', $plusmsg = 'post_date' );
//热评日志
get_posts( $orderby = 'comment_count', $plusmsg = 'commentcount' );
//随机日志
get_posts( $orderby = 'rand', $plusmsg = 'post_date' );
?>

可以看到它们三者共用一个函数,而只是参数不同罢了,如题,最新、热评、随机日志函数三体合一就完成了。

下面我介绍一下把 WordPress 的最新、热评、随机日志这三体合一的函数设置在 30 天内的时间范围里,效果就见本站上的侧边栏上的这些日志吧,都在 30 天之内。

首先把以下函数放在 WordPress 主题文件夹里的 functions.php 中:

function filter_where($where = '') {
    $where .= " AND post_date > '" . date('Y-m-d', strtotime('-30 days')) . "'";
    return $where;
}
function some_posts($orderby = '', $plusmsg = '',$limit = 10) {
    add_filter('posts_where', 'filter_where');
    $some_posts = query_posts('posts_per_page='.$limit.'&caller_get_posts=1&orderby='.$orderby);
    foreach ($some_posts as $some_post) {
            $output = '';
            $post_date = mysql2date('y年m月d日', $some_post->post_date);
            $commentcount = '('.$some_post->comment_count.' 条评论)';
            $post_title = htmlspecialchars(stripslashes($some_post->post_title));
            $permalink = get_permalink($some_post->ID);
            $output .= '<li><a href="' . $permalink . '" title="'.$post_title.'">' . $post_title . '</a>'.$$plusmsg.'</li>';
            echo $output;
        }
    wp_reset_query();
}

可以看到第二行中的 30 就是指最近 30 天,也可以根据你自己的需要修改这个时间。至于调用则和升级版之前的一样,下面只是比上次多加了一个 $limit 参数:

<?php
//最新日志
some_posts( $orderby = 'date', $plusmsg = 'post_date', 10 );
//热评日志
some_posts( $orderby = 'comment_count', $plusmsg = 'commentcount', 10 );
//随机日志
some_posts( $orderby = 'rand', $plusmsg = 'post_date', 10 );
?>

OK,接下来我要把点击最高的排行榜也改成 30 天内的排名,这样对经常来光顾的用户来说应该更合理吧,否则看来看去就那几篇,标题都看烂了。

文章作者:万戈

文章来源:http://wange.im/three-in-one-update.html 转载请注明文章出处链接和作者