今回の記事ではプラグインは一切使用せずにphpを使って人気記事を作成して表示する方法を紹介します。
プラグインを使った人気記事はWordPress Popular Postsが有名ですが、サイトへの負荷が大きくなってしますデメリットがあります。負荷を抑えて人気記事を作るには最終的にはオリジナルでphpを書いていく事が一番かと思われます。
プラグイン無しで人気記事を取得表示する方法
まず初めに人気な記事(PV数)をカウントのプログラムを作成します。カウントした記事でカウント数が多いものを出力します。そしてgooglebotなどのクローラーへのアクセスは無効にします。
そのプログラムが以下です。これをfunction.phpに記述します。
//クローラーのアクセス判別
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;
}
// 人気記事出力用関数
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';
}
// 記事viewカウント用関数
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);
次に人気記事を表示したい箇所(例えばsidebar.phpなど)に以下の記述をします。この記述はループなので、ここからはいつも通りに記事一覧を表示させるうようにtitleやthumbnailなどをループ内で取得表示して記事を並べて下さい。
するとPV数が多い順に記事が表示されます。
<?php
//クローラーとログイン時のアクセスをカウントから除外
if( !is_user_logged_in() && !is_bot() ) {
setPostViews( get_the_ID() );
}
$ranking = new WP_Query( array(
'post_type' => 'post',
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'posts_per_page' => 5
));
$num = 1;
?>
<!-- ここから人気記事表示 --!>
<ul class="ranking-article-list">
<?php while ( $ranking->have_posts() ) : $ranking->the_post(); ?>
<li><a href="<?php the_permalink(); ?>">
<div class="ranking-thumb" style="background-image:url(<?php the_post_thumbnail_url('medium'); ?>);"></div>
<div class="ranking-info">
<span><?php the_time('Y.n.j'); ?></span>
<p><?php the_title(); ?></p>
</div>
</a></li>
<?php $num++; endwhile; wp_reset_postdata(); ?>
</ul>
meta_keyの「post_views_count」は先に紹介したfunction.phpの18行目でcount_keyとして値を渡しています。
基本的な記事一覧の取得方法は以下です。
以上が「プラグイン無しで人気記事を取得表示する方法【PHP】」でした。
中級者向けの技術ですが、このような技法を覚えれば無駄なプラグインを入れなくて済んですっきりとしたWEBサイトになるのでおすすめです。