コメントのいいね数ランキングを表示する方法

Cocoonカスタマイズ集
この記事は約9分で読めます。
記事内に広告が含まれています。

はじめに

以前の記事では、プラグインなしで「いいねボタン」機能を追加する方法を紹介しました。

今回は、コメントに付けられたいいね数を集計し、いいね数の多いコメントをランキング形式で表示するショートコードを追加します。

承認済みコメントを対象に、いいね数の多い順にコメント投稿者名と記事タイトルを一覧表示します。
また、上位3件には王冠アイコンを付けて順位を分かりやすくします。

この記事では、この方法について説明します。

完成イメージ

使用方法

以下にショートコードを示します。

[my_comment_like_ranking]
オプション
オプション説明値初期値
count表示数5

実装手順

以下のコードをfunctions.phpに追加します。

// ショートコードを追加
add_shortcode('my_comment_like_ranking',  function ($atts) {
  $atts = shortcode_atts(array(
    'number' => 5,
 ), $atts);

  // いいね数の多い承認済みコメントを取得
  $comments = get_comments(array(
    'status'       => 'approve',
    'post_status'  => 'publish',
    'number'       => absint($atts['number']),
    'meta_key'     => 'my_comment_like',
    'meta_value'   => 0,
    'meta_compare' => '>',
    'meta_type'    => 'NUMERIC',
    'orderby'      => 'meta_value_num',
    'order'        => 'DESC',
 ));

  // 対象コメントがない場合は終了
  if (empty($comments)) {
    return '';
  }

  ob_start();
  ?>
  <ol class="comment-like-ranking">
    <?php foreach ($comments as $comment) :
      // コメント情報を取得
      $post_title   = get_the_title($comment->comment_post_ID);
      $comment_link = get_comment_link($comment);
      $author       = get_comment_author($comment);
      $count        = intval(get_comment_meta($comment->comment_ID, 'my_comment_like', true));
      ?>
      <li>
        <div class="comment-like-ranking__info">
          <div class="comment-like-ranking__main">
            <span class="comment-like-ranking__author"><?php echo esc_html($author ?: '名無し'); ?></span>
            <span class="comment-like-ranking__count"><?php echo esc_html(number_format_i18n($count)); ?></span>
          </div>
          <a class="comment-like-ranking__title" href="<?php echo esc_url($comment_link); ?>"><?php echo esc_html($post_title); ?></a>
        </div>
      </li>
    <?php endforeach; ?>
  </ol>
  <?php
  return ob_get_clean();
});


// フロント用JS・CSSを追加
add_action('wp_enqueue_scripts', function () {
  ob_start();
  ?>
  .comment-like-ranking {
    counter-reset: ranking;
    display: flex;
    flex-direction: column;
    gap: 12px;
    list-style: none;
    margin: 0;
    padding: 0;

    li {
      align-items: center;
      border-bottom: 1px dotted #ddd;
      counter-increment: ranking;
      display: flex;
      gap: 12px;
      padding-bottom: 12px;
      position: relative;

      &:last-child {
        border-bottom: none;
        padding-bottom: 0;
      }

      &::before {
        align-items: center;
        content: counter(ranking);
        display: flex;
        flex: 0 0 22px;
        font-weight: bold;
        height: 22px;
        justify-content: center;
        text-align: center;
      }

      &:nth-child(-n+3)::before {
        background: #999;
        border-radius: 50%;
        color: #fff;
      }

      &:nth-child(1)::before {
        background: #d4a017;
      }

      &:nth-child(2)::before {
        background: #8e99a4;
      }

      &:nth-child(3)::before {
        background: #b87333;
      }
    }

    .comment-like-ranking__info {
      flex: 1;
      min-width: 0;
    }

    .comment-like-ranking__main {
      align-items: center;
      display: flex;
      gap: 12px;
      justify-content: space-between;
    }

    .comment-like-ranking__author {
      font-weight: bold;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .comment-like-ranking__title {
      display: block;
      font-size: .8em;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .comment-like-ranking__count {
      display: flex;
      font-weight: bold;
      flex-shrink: 0;
      gap: 4px;
      white-space: nowrap;

      &::before {
        content: "\f004";
        font-family: "Font Awesome 5 Free";
        font-weight: 900;
      }
    }
  }
  <?php

  $handle = 'comment-like-ranking';

  wp_register_style($handle, false);
  wp_enqueue_style($handle);
  wp_add_inline_style($handle, ob_get_clean());
});

参考:コメント編集画面にいいね数の入力欄を追加する方法

コメント編集画面に、コメントのいいね数を手動で変更できるメタボックスを追加します。

完成イメージ

実装手順

以下のコードをfunctions.phpに追加します。

/**
 * メタボックスの入力フォームを出力
 *
 * @param WP_Comment $comment コメントオブジェクト
 * @return void
 */
function render_comment_like($comment) {
  $count = get_comment_meta($comment->comment_ID, 'my_comment_like', true);

  wp_nonce_field('comment_like_action', 'comment_like_nonce');
  ?>
  <p>
    <label for="my_comment_like">my_comment_like</label>
    <input type="number" name="my_comment_like" id="my_comment_like" value="<?php echo esc_attr( $count ); ?>" min="0" step="1" class="widefat">
  </p>
  <?php
}


// メタボックスを追加
add_action('add_meta_boxes_comment', function () {
  add_meta_box(
    'comment_like',
    'コメントいいね数',
    'render_comment_like',
    'comment',
    'normal'
  );
});


// コメントデータを保存
add_action('edit_comment', function ($comment_id) {
  // nonceチェック
  if (!isset($_POST['comment_like_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['comment_like_nonce'])), 'comment_like_action')) {
    return;
  }

  // 権限チェック
  if (!current_user_can('edit_comment', $comment_id)) {
    return;
  }

  // POSTデータを確認
  if (isset($_POST['my_comment_like'])) {
    $count = absint(wp_unslash($_POST['my_comment_like']));
    update_comment_meta($comment_id, 'my_comment_like', $count);
  }
});

さいごに

今回紹介した方法を使えば、コメントに付けられたいいね数を集計し、人気のあるコメントをランキング形式で表示できます。
ショートコードの表示件数を変更すれば、ランキングに掲載するコメント数も自由に調整できます。
コメント欄の盛り上がりを可視化する機能として、ぜひ活用してみてください。

タイトルとURLをコピーしました