@dallaslu 卢达 幻想牢骚,奇淫巧技

获取最新评论 PHP 代码

WordPress 侧栏最新评论的默认样式很不顺眼,于是从 widgets.php 中把显示评论的代码抠出来改了一番。并且过滤掉了注册用户的评论,以及 trackback 、pingback 。

先说我是怎么办的。

打开 wordpress/wp-includes/widgets.php ,搜索 wp_widget_recent_comments ,找到位于1379~1405行的函数,修改之后获得了如下代码:

<?php
global $wpdb, $comments, $comment;
$comments = $wpdb->get_results("SELECT * FROM $wpdb->comments WHERE comment_approved = '1' and user_id = '0' and comment_type = '' ORDER BY comment_date_gmt DESC LIMIT 5");
?>
<ul id="recentcomments">
<?php if ( $comments ) : foreach ( (array) $comments as $comment) :
$text = $comment->comment_author . ': ' . $comment->comment_content;
$text = mb_strimwidth(strip_tags($text), 0, 40,"...");
echo  '<li class="recentcomments"><a href="'. get_comment_link($comment->comment_ID) . '" title="《' . get_the_title($comment->comment_post_ID) . '》">' . $text . '</a></li>';
endforeach; endif;?>
</ul>

接着在 WordPress 管理首页->外观->Widgets 添加了个 Samsarin PHP Widget (),代码粘进去,OK。

下面说几个你可能用到的修改办法。

最新评论中不显示 trackback 、pingback

打开 widgets.php ,搜索 WHERE comment_approved = '1' 找到 1392行:

$comments = $wpdb->get_results("SELECT * FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT $number");

修改成:

$comments = $wpdb->get_results("SELECT * FROM $wpdb->comments WHERE comment_approved = '1' and comment_type = '' ORDER BY comment_date_gmt DESC LIMIT $number");

最新评论中不显示注册用户评论

这个方法很适合像我一样的个人博客,经常回复读者留言,结果一段时间内“最新评论”中显示的都是自己的留言。方法同上,修改为:

$comments = $wpdb->get_results("SELECT * FROM $wpdb->comments WHERE comment_approved = '1' and uesr_id = '0' ORDER BY comment_date_gmt DESC LIMIT $number");

需要注意的是,修改前请备份 widgets.php ;也把修改后的备份一下,升级程序会覆盖你修改的文件的。

9 条评论

  1. Shawn

    其实不用这么麻烦的,桑椹的中文工具箱有完整的解决方案,因为源自桑椹的 my-hacks.php,所以你可以将它们粘贴到主题的 functions.php 当中。有很多参数可选,包括截断。

  2. 这个…我是用 mg12 写的 wp-recent-comments 插件完成的,比较方便,呵呵。
    不过你的方法也不错,让我学到一些技巧,谢谢!

  3. 折腾的过程是最快乐的,这样折腾而不要拿来注意可以学到更多东西.
    其次,建议你把它放在主题的 functions.php 中,方便调用哟~

  4. 你这的评论框不记 Cookies 诶,不爽.
    最后一个,最新评论中不显示注册用户评论,有的Blog可能会有不是管理员的注册用户嘛,这样就不友好了,建议是:
    过滤的条件为,评论者的名字=管理员的名字.
    这个管理员的名字可以用PHP获得,也可以自己设置的.

  5. 我也不是很会PHP,但参考了一下其他代码,你可以这么写:

    $comments = $wpdb->get_results(”SELECT * FROM $wpdb->comments WHERE comment_approved = ‘1′ and comment_author != ‘NetPuter’ ORDER BY comment_date_gmt DESC LIMIT $number”);

    把原来的 uesr_id = ‘0′ 改成了 comment_author != ‘NetPuter’
    NetPuter就是管理员的名字~

    and 我米测试过,大概就是这么实现的,用不到SQL的说~

  6. Zdraste! Vot takoi vot u vas horoshiy sait. Spasibki.

  7. hi,如果我想获得指定文章或者页面的最新评论,不知道怎样做呢?

  8. 小虫

    是么,之前也出现过不记 Cookie 的问题,后来好了啊。想过过滤条件,最好是不显示文章作者的评论哈哈,不过我SQL很烂

发表评论

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">