• 注册
  • WordPress WordPress 关注:2 内容:19

    WordPress 个人/用户中心,调用当前用户的所有评论(附其他函数调用方式)

  • 查看作者
  • 打赏作者
    • WordPress
    • Lv.14
      帅气冲天

      问题前言

      制作wordpress个人/用户中心页面时,需要开发一个列表来显示当前用户的所有评论,要怎么弄呢?

      并且在用户中心主页展示当前登录用户的评论数量

      解决方案

      显示当前登录用户的所有评论

      <?php
      global $wpdb;
      $sql = "SELECT DISTINCT ID, post_title, post_password, comment_ID,comment_post_ID, comment_author, comment_date_gmt, comment_approved,comment_type,comment_author_url,SUBSTRING(comment_content,1,30) AS com_excerpt
      FROM $wpdb->comments
      LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID)
      WHERE  comment_approved = '1' AND comment_type = '' AND post_password = '' AND comment_author = '$current_user->display_name'
      ORDER BY comment_date_gmt DESC   LIMIT 5";
      $comments = $wpdb->get_results($sql);
      $output = $pre_HTML;
      foreach ($comments as $comment) {
      	$output .= "<li><p>".strip_tags($comment->comment_author)."说:" ."<a class=\" jccsf2\" href=\"". get_permalink($comment->ID) ."#comment-" . $comment->comment_ID . "\" title=\"留言在 " .$comment->post_title . "\">" . strip_tags($comment->com_excerpt)."</a></p></li>";
      }
      $output .= $post_HTML;
      echo $output;
      ?>

      显示当前登录用户的评论数量

      方法1:通过get_comments()函数获取

      <?php 
      global $user_ID;
      echo get_comments('count=true&user_id='.$user_ID);
      ?>

      方法2:通过$wpdb查询数据库获取

      <?php 
      global $wpdb,$user_ID;
      $count_user_comments = $wpdb->get_var( 
      $wpdb->prepare("Select count(comment_ID) from $wpdb->comments where user_id = %d", $user_ID) 
      );
      echo $count_user_comments[0];
      ?>

      以上两种方法输入的结果都是当前已登录用户的总评论数量

      其他函数调用

      调用用户名 get_the_author()

      <?php echo get_the_author() ?>

      调用用户头像 get_avatar($a,num)

      第一个参数必须是 用户/用户id/邮箱,第二个是头像大小

      下面代码是根据当前作者邮箱调用的用户头像

      <?php echo get_avatar( get_the_author_meta('email'), '200' );?>

      用户简介

      <?php if(get_the_author_meta('description')){ echo the_author_meta( 'description' );}else{echo'这个人有点懒,啥都没有写!'; }?>

      获取指定作者的文章列表网址 get_author_posts_url() 

      例如:在首页循环中,调用作者及作者用户中心的链接

      <a class="author-name" href="<?php echo get_author_posts_url( get_the_author_meta( 'ID' ) ) ?>"><?php echo get_the_author() ?></a>

      使用说明

      请根据自己实际情况做相应修改

      请登录之后再进行评论

      登录

      我关注的论坛

      暂没有数据

    • 发布内容
    • 做任务
    • 实时动态
    • 偏好设置
    • 帖子间隔 侧栏位置: