重要:本文最后更新于2019-04-05 12:46:10
,某些文章具有时效性,若有错误或已失效,请在下方留言或联系九月网。
前几天有人问我评论列表后面的楼层是怎么实现的,这东西根本不是我写的好吧。有现成的,为什么要自己写?用过大前端DUX主题的站长应该都知道,大前端dux主题的评论列表就有楼层计数功能,拿过来用不就行了?既然有人需要我还是分享下吧。大家也学习下大前端的写法,毕竟人家可是国内的大佬,值得学习。
WordPress评论列表显示楼层实现代码DUX主题同款
该文件位于dux主题目录下的modules文件夹中,名字叫做mo_comments_list.php,下面是源码。
/** * [mo_comments_list description] * @param [type] $comment [description] * @param [type] $args [description] * @param [type] $depth [description] * @return [type] [description] */ function mo_comments_list($comment, $args, $depth) { $GLOBALS['comment'] = $comment; global $commentcount, $wpdb, $post; if(!$commentcount) { //初始化楼层计数器 $page = get_query_var('cpage');//获取当前评论列表页码 $cpp = get_option('comments_per_page');//获取每页评论显示数量 $pcs = get_option('page_comments');//分页开关 $comments = $wpdb->get_results("SELECT * FROM $wpdb->comments WHERE comment_post_ID = $post->ID AND comment_type = '' AND comment_approved = '1' AND !comment_parent"); $cnt = count($comments);//获取主评论总数量 if ( get_option('comment_order') === 'desc' ) { //倒序 if (!$pcs || ceil($cnt / $cpp) == 1 || ($page > 1 && $page == ceil($cnt / $cpp))) { $commentcount = $cnt + 1;//如果评论只有1页或者是最后一页,初始值为主评论总数 } else { $commentcount = $cpp * $page + 1; } }else{ //顺序 if( !$pcs ){ $commentcount = 0; }else{ $page = $page-1; $commentcount = $cpp * $page; } } } echo '
使用方法
方法一
像dux一样,在主题目录下建立modules文件夹,然后将上面的代码保存在该文件夹中,再利用如下代码加载到WordPress中。
function _moloader($name = '', $apply = true) { if (!function_exists($name)) { include get_stylesheet_directory() . '/modules/' . $name . '.php'; } if ($apply && function_exists($name)) { $name(); } }
加载方式多种多样,直接使用include引用也是可以的。
然后通过_moloader(‘mo_comments_list’, false);来加载上面的代码,最后就是使用了。WordPress提供了评论列表加载方法wp_list_comments函数,该函数可以携带回调函数callback。
wp_list_comments('type=comment&callback=mo_comments_list');
上述代码的意思是取出评论数据,并交给回调函数mo_comments_list来处理,mo_comments_list就是上面我们的楼层计数方法,其中包含了输出评论的内容。
方法二
直接将上面的代码写在functions.php文件中,返回在文章页适当位置使用下面代码来调用。
wp_list_comments('type=comment&callback=mo_comments_list');
是不是觉得方法二简单很多呢?确实如此,只要你不嫌弃你的functions文件太大,随便你咯。