wordpress自带的近期评论小工具不会显示具体的评论内容,而且还会显示管理员的评论,感觉不是很好,只能自己处理一下。花了近一个晚上才处理好,主要用在理解小工具的原理上了,但是使用起来就非常简单了,只要简单的两个步骤。该小工具在wordpress 3.4.1版本上测试通过。先来个截图预览下:
1、制作小工具
代码一堆可以不用管它,直接将代码保存到wordpress的/wp-content/widgets/comments.php文件。
为什么放到这里呢?因为像主题、插件这些都是存在wp-content这个目录下面,小工具存放在这里可以统一管理,也符合wordpress目录规则。
复制代码代码如下:
/*** 继承WP_Widget_Recent_Comments* 这样就只需要重写widget方法就可以了*/class My_Widget_Recent_Comments extends WP_Widget_Recent_Comments {
/*** 构造方法,主要是定义小工具的名称,介绍*/function My_Widget_Recent_Comments() {$widget_ops = array('classname' => 'my_widget_recent_comments', 'description' => __('显示最新评论内容'));$this->WP_Widget('my-recent-comments', __('我的最新评论', 'my'), $widget_ops);}
/*** 小工具的渲染方法,这里就是输出评论*/function widget($args, $instance) {global $wpdb, $comments, $comment;
$cache = wp_cache_get('my_widget_recent_comments', 'widget');
if (!is_array($cache))$cache = array();
if (!isset($args['widget_id']))$args['widget_id'] = $this->id;
if (isset($cache[$args['widget_id']])) {echo $cache[$args['widget_id']];return;}
extract($args, EXTR_SKIP);$output = '';$title = apply_filters('widget_title', empty($instance['title']) ? __('Recent Comments') : $instance['title'], $instance, $this->id_base);if (empty($instance['number']) || !$number = absint($instance['number']))$number = 5;//获取评论,过滤掉管理员自己$comments = $wpdb->get_results("SELECT * FROM $wpdb->comments WHERE user_id !=2 and comment_approved = '1' and comment_type not in ('pingback','trackback') ORDER BY comment_date_gmt DESC LIMIT $number");$output .= $before_widget;if ($title)$output .= $before_title . $title . $after_title;
$output .= '
- ';if ($comments) {// Prime cache for associated posts. (Prime post term cache if we need it for permalinks.)$post_ids = array_unique(wp_list_pluck($comments, 'comment_post_ID'));_prime_post_caches($post_ids, strpos(get_option('permalink_structure'), '%category%'), false);
' . $avatar . ' ' . $author . ' 发表在 ' . $post . '
' . $content . '
';}}$output .= '
foreach ((array) $comments as $comment) {//头像$avatar = get_avatar($comment, 40);//作者名称$author = get_comment_author();//评论内容$content = apply_filters('get_comment_text', $comment->comment_content);$content = mb_strimwidth(strip_tags($content), 0, '65', '...', 'UTF-8');$content = convert_smilies($content);//评论的文章$post = '' . get_the_title($comment->comment_post_ID) . '';
//这里就是输出的html,可以根据需要自行修改$output .= '
echo $output;$cache[$args['widget_id']] = $output;wp_cache_set('my_widget_recent_comments', $cache, 'widget');}
}
//注册小工具register_widget('My_Widget_Recent_Comments');
在主题目录下的funtions.php文件中加载这个小工具:
复制代码代码如下:
require(get_template_direCTOry().'/../../widgets/comments.php');2、进入后台管理拖入评论小工具
选择外观->小工具,可以看到评论小工具就加载进来了,如下:直接将评论小工具拖动到侧边栏就OK了。
小结
有的朋友可能会担心代码出现什么问题,这个代码是从系统自带的评论小工具中复制过来的,主要是修改评论的获取和评论的显示样式。系统自带的评论小工具代码可以参考/wp-includes/default-widgets.php中的WP_Widget_Recent_Comments类。














发表评论