WordPressプラグイン「WP Ulike」で過去1週間のいいね数ランキングを表示する方法

「WP Ulike」はWordPressの記事に「いいね」機能を追加するプラグインです。

このプラグインにはいいね数順に記事を取得する関数が用意されているのですが、一部期間指定がうまく動かなかったり、いいね数が累積で出てしまうなど使いづらいところがあったため、今回独自実装を行いました。

今回のサンプルでは、期間指定は過去1週間いいね数が多い順10記事取得します。

<?php

/* いいね数多い順に記事ID取得 */
$results = $wpdb->get_results("select post_id from (select post_id as post_id, count(id) as cnt from wp_ulike where status = 'like' and date_time >= (now() - interval 7 day) group by post_id ORDER BY cnt DESC, date_time DESC LIMIT 10) as sum;");

$post_ids = null;

foreach ($results as $result) {

  $post_ids[] = $result->post_id;

}

$query = new WP_Query(array(

  'post__in' => $post_ids,
  'post_type' => 'post',
  'orderby' => 'post__in',

));

/* 記事内容取得 */
if ($query->have_posts()) {

  while ($query->have_posts()) {

    $query->the_post();

    // 記事ID
    $post_id = get_the_ID();
    echo $post_id;

    // 記事URL
    echo the_permalink();

    // アイキャッチ画像URL
    echo get_the_post_thumbnail_url( get_the_ID(), 'large' );

    // 記事タイトル
    echo the_title();

    // 公開日時
    echo the_date('Y.m.d');

    // カテゴリー名
    $categories = get_the_category();
    if($categories){
      echo $categories[0]->name;
    }

    // いいね数
    $like_count = $wpdb->get_results("select count(id) as cnt from wp_ulike where status = 'like' and date_time >= (now() - interval 7 day) and post_id = " . $post_id . ";");
    echo $like_count;

  }

  wp_reset_postdata();

}

?>

設定を変更したい場合は上記2箇所あるSQL文を変更いただけばOKです。