0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Wordpressのブログ記事につけるタグを、人気順(view数順)に表示させたい

Posted at

プラグインWP-PostViewsを入れる

デフォルトではWordpressはタグの閲覧数を集計していないので、プラグインを入れてタグごとの閲覧数を集計する機能を追加します。

https://ja.wordpress.org/plugins/wp-postviews/

カスタム関数をfunction.phpに定義する

全件取得することもないと思うので、上位5件のみ取得する様にしてみます。

function.php
function get_tags_view_count() {
    $tags = get_tags();
    $tag_counts = array();

    foreach ($tags as $tag) {
        $args = array(
            'tag_id' => $tag->term_id,
            'posts_per_page' => -1
        );

        $query = new WP_Query($args);
        $count = 0;

        if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post();
            $post_id = get_the_ID();
            $count += (int) get_post_meta($post_id, 'views', true);
        endwhile; endif;

        $tag_counts[$tag->name] = $count;
        wp_reset_postdata();
    }

    arsort($tag_counts);
    return array_slice($tag_counts, 0, 5, true); // 上位5件のみを返す
}

実際に表示するページでカスタム関数を呼び出す

<?php
$tag_counts = get_tags_view_count();
echo '<ul>';
foreach ($tag_counts as $tag_name => $count) {
    $tag_obj = get_term_by('name', $tag_name, 'post_tag');  // タグ名からタグオブジェクトを取得
    $tag_link = get_tag_link($tag_obj->term_id);            // タグのリンクURLを取得
    echo '<li><a href="' . esc_url($tag_link) . '">' . esc_html($tag_name) . '</a></li>';
}
echo '</ul>';
?>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?