閲覧回数をデータベースにカウントしていく方法
①functions.phpに以下のコードを書く
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
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); |
②表示させたい場所に以下のコードを書く
1 2 3 4 5 |
<?php // views post metaで記事の情報を取得する setPostViews(get_the_ID()); echo getPostViews(get_the_ID()) ; ?> |