「コメント数」タグアーカイブ

コメントページの上のコメント数を「あなたの記事に書かれた、他ユーザーのコメント数」のみカウントする方法 WordPress BuddyPressカスタマイズメモ

管理画面のコメントページでコメント数は「あなたの記事に書かれた、他ユーザーのコメント数」のみカウントさせる

WordPressのSNSプラグイン、BuddyPressを導入すると不特定多数のメンバーが参加することになる。

他人の記事へのコメントを、投稿者に見せる必要はないので、それを非表示にした上で、コメントページの上にある、コメント数のカウントを自分の投稿へのコメントのみカウントするようにする。
 

functions.php へ記述

//投稿者のみ、コメントを「自分の投稿」へのコメント数のみカウント

function myblogs_comments_count() {
 global $pagenow;
 if(is_admin() && current_user_can( 'author' )){ //管理画面かつ投稿者権限の場合
  global $user_ID;
  get_currentuserinfo();
  if ( false === ( $stats = get_transient( 'myblogs_author'.$user_ID.'_comments' ) ) ) {
   $stats = array('moderated'=>0,'approved'=>0,'post-trashed'=>0,'trash'=>0,'total_comments'=>0,'spam'=>0);
   $the_query = new WP_Query( array('author' => $user_ID,'posts_per_page' => -1) );
   if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post();
    $comments = myblogs_count_comments(get_the_id()); //それぞれの状態のコメントをカウント
    $stats['moderated'] = $stats['moderated'] + $comments->moderated;
    $stats['approved'] = $stats['approved'] + $comments->approved;
    $stats['post-trashed'] = $stats['post-trashed'] + $comments->{'post-trashed'};
    $stats['trash'] = $stats['trash'] + $comments->trash;
    $stats['total_comments'] = $stats['total_comments'] + $comments->total_comments;
    $stats['spam'] = $stats['spam'] + $comments->spam;
   endwhile;
   endif;
   wp_reset_postdata();
   set_transient( 'myblogs_author'.$user_ID.'_comments', $stats, 60 * 30 );
  }
  return (object) $stats;
 }
}
add_filter('wp_count_comments','myblogs_comments_count');

//「自分の投稿」へのコメント数をカウントの後半

function myblogs_count_comments( $post_id = 0 ) {
 global $wpdb;
 $post_id = (int) $post_id;
 if ( !empty($stats) )
  return $stats;
  $count = wp_cache_get("comments-{$post_id}", 'counts');
 if ( false !== $count )
  return $count;
  $where = '';
 if ( $post_id > 0 )
  $where = $wpdb->prepare( "WHERE comment_post_ID = %d", $post_id );   $count = $wpdb->get_results( "SELECT comment_approved, COUNT( * ) AS num_comments FROM {$wpdb->comments} {$where} GROUP BY comment_approved", ARRAY_A );
  $total = 0;
  $approved = array('0' => 'moderated', '1' => 'approved', 'spam' => 'spam', 'trash' => 'trash', 'post-trashed' => 'post-trashed');
 foreach ( (array) $count as $row ) { // 全てで、ゴミ箱のものはカウントしない
  if ( 'post-trashed' != $row['comment_approved'] && 'trash' != $row['comment_approved'] )
   $total += $row['num_comments'];
  if ( isset( $approved[$row['comment_approved']] ) )
   $stats[$approved[$row['comment_approved']]] = $row['num_comments'];
 }
 $stats['total_comments'] = $total;
 foreach ( $approved as $key ) {
  if ( empty($stats[$key]) )
   $stats[$key] = 0;
 }
 $stats = (object) $stats;
 wp_cache_set("comments-{$post_id}", $stats, 'counts');
 return $stats;
}

 
なお、
「コメント」に、「あなたの記事に他ユーザーが書いたコメント」のみを表示させる方法はこちらを参照。