用get_comments实现WordPress带头像最新评论

GD Star Rating
loading...

前一段在制作zAlive主题的时候需要一个带头像最新评论widget,网上Google了一大圈发现用的最多的是SQL,我也就直接拿来用了,而且神奇的是通过了WP的主题审核,但是后来在更新主题的时候怕不给通过,就索性找别的方法,也就是今天的主角,get_comments()

其实用get_comments()实现WordPress带头像最新评论zww很早就有一篇文章介绍,但是从2010年到现在WP已经升级了N多个版本,原来的参数有的已经失效,于是我就重新翻阅文档,用新版的get_comments实现WordPress带头像最新评论。

我写的这个可以指定获取的评论数,头像尺寸,评论字符数

function zAlive_recentComments($count,$avatarSize,$excerptLength){
    $comments;
    if( $count != 0 ){
      //新版的get_comments()不能直接获取指定类型的评论(比如会获取到pingback/trackback),+30是为了多获取一些评论,从而减少获取不到指定数量的评论的机会
      $comments = get_comments( apply_filters( 'widget_comments_args', array( 'number' => $count + 30, 'status' => 'approve', 'post_status' => 'publish' ) ) );
    }
    $valid_comments_number = 0;//有效评论数
    $output = '';
    if( !empty ( $comments ) ){
      foreach ($comments as $comment) {
        $post = get_post( $comment->comment_post_ID );
        //评论不是pingback或trackback并且评论所属文章没有密码保护
        if( empty ($comment->comment_type ) && empty ( $post->post_password ) ){
          $output .= '<li class="clearfix">'. get_avatar($comment, $avatarSize) .'<div class="comment-data"><a class="title" href="' . get_permalink($comment->comment_post_ID) . "#comment-" . $comment->comment_ID . '" title="on ' . strip_tags( $post->post_title) . '">' . wp_html_excerpt( strip_tags ( $comment->comment_content), $excerptLength ) . '</a>' .'<span class="comment_author detailed visible-desktop">From <span class="author">' . $comment->comment_author . '</span>&nbsp;&nbsp;<span class="date">' . $comment->comment_date . "</span></span></div></li>";
          $valid_comments_number++;
          if( $valid_comments_number == $count )
            break;
        }
      }
    }
    $output = convert_smilies($output);
    echo $output;
  }

然后就是调用了,比如zAlive_recentComments(10,40,100)

用get_comments实现WordPress带头像最新评论, 4.5 out of 5 based on 2 ratings

已有5条评论 发表评论

  1. 断桥残雪 /

    ok,学习了。挺不错的。

    GD Star Rating
    loading...
  2. 集趣 /

    这方法的确不错哦

    GD Star Rating
    loading...
  3. 菠萝 /

    哈哈,这个很实用。。。

    GD Star Rating
    loading...
  4. 一米 /

    修改主题呢,刚用上。

    GD Star Rating
    loading...
  5. 记忆碎片 /

    这个蛮不错的

    GD Star Rating
    loading...

回复给断桥残雪 取消回复