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
コメント