『プラグインなし』で人気記事一覧を出力する方法【WordPress】
WordPressで人気記事を出力するといったらwordpress-popular-postsのプラグインが有名です。しかし、「プラグインに頼りすぎてはいけない」ということで人気記事一覧が出力できるコードを書きました。
たったの2ステップで完成します。
完成イメージは以下のような感じです( ◜◡‾)
さっそくまとめ開始。
STEP1: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);
STEP2:人気記事一覧を出力する
人気な記事一覧を出力したい部分に以下のコードをコピペでOK。
<?php
// views post metaで記事のPV情報を取得する
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(); ?>
<!-- サムネイルの表示 -->
<div class="col-sm-4 col-xs-4">
<a href="<?php echo get_permalink(); ?>">
<?php if ( has_post_thumbnail() ) { the_post_thumbnail( 'post-thumbnail'); } ?>
</a>
</div>
<!-- タイトルの表示 -->
<div class="col-sm-8 col-xs-8">
<p>
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a>
</p>
</div>
<?php endwhile; ?>
な、、なんとこれだけで完成です。
ノープラグイン生活を楽しみましょう。
※参考記事
・Most popular posts using views post meta
・Track post views without a plugin using post meta