Như các bạn đã biết mặc định wordpress không cung cấp tính năng hiển thị lượt xem ở từng bài viết (post) hay từng trang (page) .Nếu bạn không muốn sử dụng plugin thì hôm nay mình xin cung cấp cho các bạn cách hiển thị lượt xem dễ dàng
Bước 1 Bỏ hàm này vào file 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 issues with prefetching adding extra views
remove_action( ‘wp_head’, ‘adjacent_posts_rel_link_wp_head’, 10, 0);
Bước 2 Gọi hàm này ở file single.php và nhớ để nó nằm trong vòng lập
setPostViews(get_the_ID());
Bước 3 gọi hàm này ra những chỗ cần hiển thị
echo getPostViews(get_the_ID());
Chúc các bạn thành công