WordPress通过根据评论数量判断是否显示评论者链接

这个功能是,你可以根据评论数来控制是否显示留言者的链接。比如说只有当留言者的评论数大于等于 1024 的时候才显示链接,否则不显示。当然,1024 只是个传说,你可以根据实际修改。

大发的这段代码真是被抄袭了无数次,我是连名称都懒得改了。。

这里评论数肯定要根据邮箱来统计了,于是最基本的思路就是根据邮箱来获取评论数,然后再根据评论数获取邮件链接,虽然能达到效果,但是非常不科学,这样每条评论都会去查询一次,非常耗费性能,对于个人博客来说可能影响不是很大,但是有更好的解决方案那最好就不使用这个方法了。

我的思路是把判断过程放在发布评论的时候,然后设置一个白名单,如果评论数大于指定数值,则把这个邮箱加入到白名单中。然后根据这个白名单来控制是否显示评论者的链接。这样就做到了性能最优。

将以下代码加入 functions.php 中即可:

function fa_is_friend( $email = null , $num = 5 ){
    $count = get_comments(array(
        'author_email' => $email,
        'count' => true,
    ));

    return ( $count > $num );
}

function fa_update_friend_list( $comment_id ){
    $comment = get_comment($comment_id);
    $friend_list = get_option('friend_list') ? get_option('friend_list') : array();
    $email = $comment->comment_author_email;
    if ( fa_is_friend($email) && !in_array( $email , $friend_list) ) {
        $friend_list[] = $email;
        update_option('friend_list',$friend_list);
    }
}
add_action('comment_post', 'fa_update_friend_list');


function fa_show_friend_link( $return , $author, $comment_ID ){
    $comment = get_comment( $comment_ID );
    $email = $comment->comment_author_email;
    $friend_list = get_option('friend_list') ? get_option('friend_list') : array();
    if ( in_array($email,$friend_list) ) {
        return $return;
    } else {
        return $author;
    }
}
add_filter('get_comment_author_link','fa_show_friend_link',10,3);

function fa_is_friend这个函数第二个变量num 就是控制显示的数量,根据你的需要酌情处理。

注意本方法仅适合使用the_author_link()来输出评论者昵称的主题,一般来讲,标准主题都会使用这个函数。如果你使用了自定义拼接的 html 只需要再加个邮箱是否在白名单的判断即可。

注:如果添加了此代码,则之前所有的评论都是将不显示评论链接,只有当访客发表新的评论后,若评论数量达标则以前所有的评论都会显示链接!

未经允许不得转载:主机格调 » WordPress通过根据评论数量判断是否显示评论者链接

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏