人気記事を作るには記事が表示された際にカスタムフィールドに加算していくようにするだけ。
人気記事のfunctions.php設定
functions.phpに以下のコードを追記する。対応するkeyのカスタムフィールドがない場合は新しく作成する。
2つめの関数でwp_head
が実行されるときにカウントを実行するように設定。
function my_popular_post_counter($post_id) {
$count_key = 'view_count';
$count = get_post_meta($post_id, $count_key, true);
if ($count == '') {
$count = 0;
delete_post_meta($post_id, $count_key);
add_post_meta($post_id, $count_key, '0');
} else {
$count++;
update_post_meta($post_id, $count_key, $count);
}
}
function my_popular_post_trigger($post_id) {
if (!is_single()) return;
if (empty($post_id)) {
global $post;
$post_id = $post->ID;
}
my_popular_post_counter($post_id);
}
add_action('wp_head', 'my_popular_post_trigger');
テンプレートに表示
テンプレートにランキングを表示するには、WP_Query()
でクエリを実行するだけ。
画面が表示されるたびにカウントするので、リロードを繰り返すとランクが変わるのがわかる。
<h3>人気記事</h3>
<ul>
<?php
$args = array(
'orderby'=>'meta_value_num',
'order' => 'DESC',
'showposts' => 5,
'meta_key'=>'view_count',
);
$wp_query = new WP_Query( $args );
if ($wp_query->have_posts()) : while ($wp_query->have_posts()) :
$wp_query->the_post(); ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; endif; wp_reset_postdata();?>
</ul>