star back image
people4
電飾 電飾
moon
men
人気記事ランキング面白いことがいっぱい

【WordPress】人気記事ランキングを表示させたい

BLOG WordPress
読了約:19分

このアウトロウェーブBlogの人気記事ランキングを表示させたい(ΦωΦ)キラーン!

活気があるように見えるかもしれないじゃないですか。

そうやって擬態して、強いもののふりをする宇宙生命体を知ってますが、本当に大切なのは心です。あなたには愛が欠けていますね。

ロボットを騙そうとしても無駄です。

やったことを記事にするのです。
人生を背負い投げ!

プラグインは使いたくないです

検索すると方法は沢山ヒットしました。その中でも特にわかりやすかったPlusersさんと、しろいぽんずさん、Bamboo Worksさんのブログを参考にしました。ありがとうございます。

要件は以下です。

  • サイドバーにランキングを表示したい。
  • 5位まで表示させたい。
  • 管理画面の記事一覧にview数を追加したい。
  • 自分のアクセスは除外しない。(自分くらいしかアクセスないので。。)

以下、作業ファイルと追加ソースになります。

ソースコードを追加しよう

■ WPテーマ内のファイル:function.php

function.phpへ下のコードを追加します。

// 記事閲覧数を取得し
function getPostViews($postID){
  $count_key = 'post_views_count';
  $count = get_post_meta($postID, $count_key, true);
  if($count==''){
      delete_post_meta($postID, $count_key);
      add_post_meta($postID, $count_key, '0');
      return "0 View";
  }
  return $count.' Views';
}
// 記事閲覧数を保存する
function setPostViews($postID) {
  $count_key = 'post_views_count';
  $count = get_post_meta($postID, $count_key, true);
  if($count==''){
      $count = 0;
      delete_post_meta($postID, $count_key);
      add_post_meta($postID, $count_key, '0');
  }else{
      $count++;
      update_post_meta($postID, $count_key, $count);
  }
}
// headに出力される前後のページへのリンクを出力するタグを削除(閲覧数を重複してカウントするのを防止するため)
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
// クローラーの除外アクセス判別
function is_bot() {
  $ua = $_SERVER['HTTP_USER_AGENT'];

  $bot = array(
        "googlebot",
        "msnbot",
        "yahoo"
  );
  foreach( $bot as $bot ) {
    if (stripos( $ua, $bot ) !== false){
      return true;
    }
  }
  return false;
}
// WPの管理画面の列にViews数を追加
add_filter('manage_posts_columns', 'posts_column_views');
add_action('manage_posts_custom_column', 'posts_custom_column_views',5,2);
function posts_column_views($defaults){
    $defaults['post_views'] = __('Views');
    return $defaults;
}
function posts_custom_column_views($column_name, $id){
    if($column_name === 'post_views'){
        echo getPostViews(get_the_ID());
    }
}

私にはPHPのおまじない。よくわかってないですが、わかりやすく書いているブログを拝見し、何とか前進できる感じです。

次は、自分のアクセスをカウントから除外できるという情報です。

■ WPテーマ内のファイル:single.php

single.phpの<?php get_header(); ?>の直前に下のコードを追加。

<?php
if( !is_user_logged_in() && !is_bot() ) {
setPostViews(get_the_ID());
} ?><?php setPostViews(get_the_ID()); ?>

自分くらいしかアクセスがないので、私は使いません。記事を書いた後の1アクセス・1カウントUp。それは私です。

次は表示させたい場所に追加するソースです。
ブログのサイドエリアに表示させたいです。

■ WPテーマ内のファイル:sidebar.php

sidebar.phpの表示させたい場所へ下のコードを追加します。

<section class="widget">
  <h2 class="wp-block-heading">よく見られている記事</h2>
  <div class="ranking">
    <ul>
      <?php
      // メインループを一時的に保持
      $original_query = $wp_query;

      // 人気記事を取得するクエリを設定
      $args = array(
        'post_type' => 'post',
        'posts_per_page' => 5, // 表示する記事数
        'orderby' => 'meta_value_num', // アクセス数によるソート
        'meta_key' => 'post_views_count' // アクセス数メタフィールド
      );
      $popular_query = new WP_Query($args);

      // 人気記事を表示
      if ($popular_query->have_posts()) :
        while ($popular_query->have_posts()) : $popular_query->the_post();
      ?>
        <li>
          <a href="<?php the_permalink(); ?>">
            <?php if (has_post_thumbnail()) : ?>
              <div class="imgss">
                <?php the_post_thumbnail('large'); ?>
              </div>
              <div class="txt_box"><?php the_title(); ?><span class="views_count"><?php echo getPostViews(get_the_ID());?></span></div>
            <?php else : ?>
                <div class="nonimg">
                  <img src="https://astrowave.jp/design/images/design_sample.jpg" alt="No images" width="480" height="300" loading="lazy">
                </div>
                <div class="txt_box"><?php the_title(); ?><span class="views_count"><?php echo getPostViews(get_the_ID());?></span></div>
            <?php endif ; ?>
          </a>
        </li>
      <?php
        endwhile;
      endif;

      // メインループを元に戻す
      $wp_query = $original_query;
      wp_reset_postdata();
      ?>
    </ul>
  </div>
</section>
ここまで仕込めたら、サイドバーに何かしら表示されていると思います。
仕込んだ時からのカウントアップとなりますので、色々と記事を表示させてみると、その通りにランキング順位が変わってくるところを、目の当たりにすることでしょう。

あとはデザイン表示。cssを好きなように適当な形で仕込みましょう。

■ css

.ranking .nonimg{
	position: relative;
	display: block;
}
.ranking .nonimg::before{
	content: "NO IMAGE";
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translateY(-50%) translateX(-50%);
	font-family: "D14MI";
	font-size: 14px;
	color: #fff;
	opacity: 0.5;
	z-index: 1;
}
.ranking ul {
	margin: 0 0 1.75em 0;
	padding: 0;
	list-style: none;
}
.views_count {
	display: none;
}
.ranking a {
	display: flex;
}
.ranking li:not(:last-child) a {
	margin: 0 0 20px;
}
.ranking .nonimg,
.ranking .imgss {
	width: 30%;
	position: relative;
}
.txt_box {
	width: 65%;
	margin: 0 0 0 5%;
}
.ranking ul li:nth-child(1) .nonimg::after,
.ranking ul li:nth-child(1) .imgss::after {
	position: absolute;
	top: 1px;
	left: 1px;
	content: "1";
	min-width: 25px;
	height: 25px;
	line-height: 26px;
	text-align: center;
	display: block;
	background: #FEB20A;
	color: #fff;
	font-weight: bold;
	z-index: 1;
}
.ranking ul li:nth-child(2) .nonimg::after,
.ranking ul li:nth-child(2) .imgss::after {
	position: absolute;
	top: 1px;
	left: 1px;
	content: "2";
	min-width: 25px;
	height: 25px;
	line-height: 26px;
	text-align: center;
	display: block;
	background: #085baf;
	color: #fff;
	font-weight: bold;
	z-index: 1;
}
.ranking ul li:nth-child(3) .nonimg::after,
.ranking ul li:nth-child(3) .imgss::after {
	position: absolute;
	top: 1px;
	left: 1px;
	content: "3";
	min-width: 25px;
	height: 25px;
	line-height: 26px;
	text-align: center;
	display: block;
	background: #000;
	color: #fff;
	font-weight: bold;
	z-index: 1;
}
.ranking ul li:nth-child(4) .nonimg::after,
.ranking ul li:nth-child(4) .imgss::after {
	position: absolute;
	top: 1px;
	left: 1px;
	content: "4";
	min-width: 25px;
	height: 25px;
	line-height: 26px;
	text-align: center;
	display: block;
	background: #000;
	color: #fff;
	font-weight: bold;
	z-index: 1;
}
.ranking ul li:nth-child(5) .nonimg::after,
.ranking ul li:nth-child(5) .imgss::after {
	position: absolute;
	top: 1px;
	left: 1px;
	content: "5";
	min-width: 25px;
	height: 25px;
	line-height: 26px;
	text-align: center;
	display: block;
	background: #000;
	color: #fff;
	font-weight: bold;
	z-index: 1;
}
.ranking .nonimg img,
.ranking .imgss img {
	width: 100%;
	height: auto;
	opacity: 1;
	transition: opacity .3s;
	border: 1px solid #000;
}

以下のように仕込めました。

view数も表示できるのですが、とても少ないので中止です。

参考にさせて頂いたブログを以下に貼り付けます。

参考:Plusers
WordPressの記事のアクセス数をプラグインなしで計測し人気記事ランキングを出力する
https://plusers.jp/blog/wordpress-popular-posts

参考:しろいぽんず
【wordpress】記事ごとの閲覧数を管理者ページから確認できるようにする
https://shiroi-ponzu.com/wordpress/wordpress-postviews/

参考:Bamboo Works
WordPressでプラグインを使わずに人気記事一覧を表示する方法
https://bambooworks.co/wordpress-popular-posts-without-plugin/

星間旅路のメロディ

「宇宙の静けさに包まれながら、漂流する過去の音楽を捜し求め、銀河の奥底でその旋律に耳を傾ける。」

「この電波はどこの星からきたのだろうか。」

どこかで聞いたことがあるような。