functions.php
// 記事のPVを取得
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';
}
// 記事のPVをカウントする
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
if (!is_user_logged_in() && !is_robots()) {
setPostViews(get_the_ID());
}
任意のxxx.php
<h4>よく読まれている記事</h4>
<hr>
<?php $args = ['post_type'=>'post','meta_key'=>'post_views_count','orderby'=>'meta_value_num','posts_per_page'=> 5,'order'=>'DESC','post_status'=>'publish'];?>
<?php $the_view_query = new WP_Query( $args );?>
<?php if ($the_view_query->have_posts()) {?>
<?php while($the_view_query->have_posts()) { ?>
<?php $the_view_query->the_post();?>
<!-- タイトル表示 -->
<div>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<p><?php echo getPostViews($post->ID); ?></p>
</div>
<?php } ?>
<?php } ?>
<?php wp_reset_postdata();?>
前日pv
https://dev.ore-shika.com/post/wp-last-pv/