Count WordPress post views?
Are you looking to create a page/post view counter to track blog/website traffic?
The best way to do that is to display the number of views right in the page or post.
Step 1: Insert the following view count code and view count function in the functions.php file of the selected theme
<code>
function getPostViews($postID){ // hàm này dùng để lấy số người đã xem qua bài viết
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){ // Nếu như lượt xem không có
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
return "0"; // giá trị trả về bằng 0
}
return $count; // Trả về giá trị lượt xem
}
function setPostViews($postID) {// hàm này dùng để set và update số lượt người xem bài viết.
$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++; // cộng đồn view
update_post_meta($postID, $count_key, $count); // update count
}
}
</code><div>
<span>1</span><span>2</span><span>3</span><span>4</span><span>5</span><span>6</span><span>7</span><span>8</span><span>9</span><span>10</span><span>11</span><span>12</span><span>13</span><span>14</span><span>15</span><span>16</span><span>17</span><span>18</span><span>19</span><span>20</span><span>21</span><span>22</span><span>23</span>
</div>
Step 2: Paste the following snippet into the single.php file just below the get_header() function ;
<?php setPostViews(get_the_ID()); ?>
Step 3: Insert the following code where you want to display
Here I will show it in the article details.
You open the single.php file again and find the code that displays the post meta: date, author, …
<?php echo getPostViews(get_the_ID()); ?>
Epilogue
Do you know another more efficient solution to create a post/page view counter in WordPress ?
Feel free to share with us using the comment box below.
If you find it interesting, you can follow the wordpress tips section to know more new knowledge.
Follow fanpage to receive the latest posts: Group
Wish you have interesting and interesting knowledge about wordpress!

