誰かのためにデザインをして、なにかを作る。
そうして過ごす時間が好きです。

プラグインなしでWordPressに人気記事ランキングを実装

プラグインなしでWordPressに人気記事ランキングを実装

PV(ページビュー)数をカウントして、多い順に表示するリストを実装します。

人気ランキング実装方法

動かすためのphpコードを設定

functions.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);
	}
}
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);

single.phpのループ内に記入

<?php if ( have_posts() ) : ?>
<?php while ( have_posts() ) : the_post(); ?>

....

<?php endwhile; ?>
<?php endif; ?>

single.php内にある上記のようなループの中に以下のコードを記入します。

<?php
    setPostViews(get_the_ID());
?>

記事の閲覧数をカウントさせるためのコードなので、忘れると順位がうまく変動しません。

表示させたい場所にコードを記入

<ul class="pv_ranking">
<?php
  setPostViews(get_the_ID()); query_posts('meta_key=post_views_count&orderby=meta_value_num&posts_per_page=5&order=DESC'); while(have_posts()) : the_post(); ?>
    <li>
        <a class="pv_ranking_img" href="<?php echo get_permalink(); ?>"><?php if ( has_post_thumbnail() ) { the_post_thumbnail( 'thumbnail'); } ?></a><a class="pv_ranking_title" href="<?php echo get_permalink(); ?>"><?php the_title(); ?></a>
    </li>
    <?php endwhile; ?>
</ul>

query_postsにあるposts_per_pageの数値を変えると表示する記事の数を変更できます。

また、post_typeを追記するとカスタム投稿を表示させることもできます。

外観CSSはお好みで設定をどうぞ!

おわりに

プラグインに頼らないことによって、テーマ制作のついでに気軽に実装できるのはありがたいですよね。

参考

How To Track Post Views Without a Plugin Using Post Meta

BACK SCROLL