「人気記事」を「新着情報」と同じ形式で表示する方法

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

はじめに

「人気記事」を「記事情報」と同じ形式で表示する機能を追加します。
この記事では、この方法について説明します。

完成イメージ

使用方法

actionオプションを追加します。

[info_list action="popular"]

実装手順

以下のコードをfunctions.phpに追加します。
集計期間は「全期間」となります。

  • ラベル
    PHPを追加(人気順並び替え)

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

    add_filter('get_info_list_args', function($args) {
      if (isset($args['action']) && $args['action'] == 'popular') {
    
        // ランキングデータを取得
        $records = get_access_ranking_records('all', $args['posts_per_page'], 'post');
    
        // IDだけの配列にする
        $post_ids = $records ? wp_list_pluck($records, 'ID') : [];
    
        if (empty($post_ids)) {
          // 投稿がない場合、ループさせない
          $post_ids = [0];
        }
        $args['orderby'] = 'post__in';
        $args['post__in'] = $post_ids;
      }
    
      return $args;
    });
  • ラベル
    PHPを追加(PV数を表示)

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

    global $current_action;
    $current_action = '';
    
    // ショートコード実行前にglobalにセット
    add_filter('pre_do_shortcode_tag', function($shortcode, $tag, $attr) {
      global $current_action;
    
      if ($tag === 'info_list') {
        $current_action = $attr['action'] ?? '';
      }
    
      return $shortcode;
    }, 10, 3);
    
    
    // ショートコード実行後にglobalをクリア
    add_filter('do_shortcode_tag', function($output, $tag, $attr, $m) {
      global $current_action;
    
      if ($tag === 'info_list') {
        $current_action = '';
      }
    
      return $output;
    }, 10, 4);
    
    
    // コメント数を追加
    add_action('info_list_item_meta_before', function() {
      global $current_actiont;
    
      if ($current_action === 'popular') {
        $pv = get_all_pv();
        $pv_unit = ($pv == '1') ? 'view' : 'views';
        $pv_text = $pv.' '.$pv_unit;
        $pv_text = apply_filters('popular_entry_card_pv_text', $pv_text, $pv, $pv_unit);
        echo '<span class="popular-entry-card-pv widget-entry-card-pv">' . $pv_text . '</span>';
      }
    }, 10, 2);
    

さいごに

今回紹介した方法を使えば、「新着情報」と同じ形式で人気記事を簡単に表示できます。
見た目の統一感を保ちながら、ユーザーが関心を持つ人気コンテンツを効率よく提示できるのが魅力です。

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