Nếu bạn có nhu cầu đếm chính xác lượt xem của bài viết WordPress, bài viết này sẽ giúp bạn.

Làm bộ đếm lượt xem chính xác cho bài viết WordPress sử dụng Ajax

Khá lâu về trước mình có giới thiệu cách đếm lượt xem bài viết WordPress không cần Plugins, nhưng nhược điểm của cách này là không hoạt động nếu bạn sử dụng hệ thống Cache. Lần này, chúng ta sẽ dùng Ajax để đếm chính xác hơn.

Xem demo:

Trong bài này, mình sẽ sử dụng Advanced Custom Fields (ACF) để lưu trữ dữ liệu lượt xem.

ACF

PHP

Đầu tiên, bạn cần khai báo phương thức đếm lượt xem tại functions.php.

/**
 * Count view via AJAX
 */
add_action('wp_ajax_countview', 'count_view');
add_action('wp_ajax_nopriv_countview', 'count_view');
function count_view() {
    $post_id = intval($_POST['postid']);
    $r_data = array();
    if (is_numeric($post_id)) {
        $view = up_view_post($post_id);
        $r_data = array('count' => 'success', 'view' => $view);
    } else {
        $r_data = array('count' => 'fail');
    }
    wp_send_json_success($r_data);
    die();
}

/**
 * Update post view
 */
function up_view_post($id) {
    $view = intval(get_field('post_view', $id));
    if (!$view) $view = 0;
    $view++;
    update_field('post_view', $view, $id);
    return $view;
}

JS

Các bạn bỏ đoạn mã sau vào footer.php.

<?php if (is_singular('post')) : ?>
<script type="text/javascript">
    $(document).ready(function() {
        $.ajax({
            type: 'post',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'countview',
                'postid': <?php the_ID(); ?>
            },
            success: function(response) {
                if (response.data.count == 'success') {
                    setView(parseInt(convertView($('#post-view').text())), parseInt(response.data.view));
                }
            }
        });

        function setView(from, to) { // Cho số chạy tới đích
            var delay = Math.ceil(1000 / (to - from));
            if (delay > 100) delay = 100;
            var myInt = setInterval(function() {
                if (from < to) {
                    from++;
                    $('#post-view').text(numberWithCommas(from));
                } else {
                    clearInterval(myInt);
                }
            }, delay);
        }

        function convertView(val) { // Quy đổi lượt xem thành số, ví dụ: 10k = 10.000
            var multiplier = val.substr(-1).toLowerCase();
            var num = 0;
            if (multiplier == "k") {
                num = parseFloat(val) * 1000;
            } else if (multiplier == "m") {
                num = parseFloat(val) * 1000000;
            } else if (multiplier == "b") {
                num = parseFloat(val) * 1000000000;
            } else {
                num = val;
            }
            return num;
        }

        function numberWithCommas(x) { // Thêm dấu . mỗi 3 chữ số
            return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
        }
    });
</script>
<?php endif; ?>

Với $('#post-view').text() là dữ liệu từ thẻ đang hiển thị số lượt xem, có thể đã được định dạng thành K, M, B, T. Chúc các bạn thành công!