Mở file functions.php trong child theme của bạn (nếu chưa có child theme, bạn nên tạo child theme để tránh mất thay đổi khi update theme). Thêm đoạn code sau:
// Thêm cột "Views" vào danh sách bài viết trong Dashboard
add_filter('manage_posts_columns', 'posts_column_views');
add_action('manage_posts_custom_column', 'posts_custom_column_views', 5, 2);
function posts_column_views($defaults){
$defaults['post_views'] = __('Views'); // Thêm cột "Views"
return $defaults;
}
function posts_custom_column_views($column_name, $post_id){
if ($column_name === 'post_views') {
echo getPostViews($post_id); // Hiển thị số lượt xem
}
}
// Hàm lấy số lượt xem của bài viết
function getPostViews($postID) {
$count = get_post_meta($postID, 'post_views_count', true);
return ($count) ? $count : 0;
}
// Hàm tăng số lượt xem mỗi khi có người truy cập bài viết
function setPostViews($postID) {
$count = get_post_meta($postID, 'post_views_count', true);
$count = ($count) ? $count + 1 : 1;
update_post_meta($postID, 'post_views_count', $count);
}
// Gọi hàm setPostViews() trong single.php để tăng số lượt xem khi có người đọc bài
add_action('wp_head', function() {
if (is_single()) {
setPostViews(get_the_ID());
}
});
Chào ! Bạn thấy nội dung này thế nào?





