Thêm bộ đếm và hiển thị số lượt xem các sản phẩm theme Flatsome không dùng plugin

Thêm bộ đếm và hiển thị số lượt xem các sản phẩm theme Flatsome không dùng plugin

Hiển thị lượt xem (views) thường phổ biến ở những trang web tin tức, blog,… Tuy nhiên WordPress lại không hỗ trợ sẵn phần này và nếu muốn có bạn phải cài thêm các plugin khác. Trong bài viết này mình sẽ giới thiệu đến bạn đếm lượt xem và hiển thị ra trong sản phẩm số view của sản phẩm đó mà không cần dùng đến plugin. Cụ thể trong bài này mình sẽ hướng dẫn các bạn làm trên theme Flatsome.

Thêm code đếm và hiển thị số lượt xem bài viết

Bước 1: Chèn code đếm lượt xem vào cuối file function.php của theme Flatsome. Lưu ý chỉ nên sử dụng child theme để sau này nâng cấp đỡ gặp vấn đề nhé

//code lấy lượt xem
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 "01 lượt xem";
    }
    return $count.' lượt xem';
}
// code đếm lượt xem
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);
    }
}
// code hiển thị số lượt xem 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');
    return $defaults;
}
function posts_custom_column_views($column_name, $id){
    if($column_name === 'post_views'){
        echo getPostViews(get_the_ID());
    }
}

Bước 2: Tìm file: flatsome\woocommerce\content-single-product.php thêm vào dòng 22 đoạn sau :

<?php setPostViews(get_the_ID()); ?>

Bước 3: Thêm code sau vào file function.php ( Như file ở bước 1 )

function action_woocommerce_single_product_summary(  ) {
echo '';
echo getPostViews(get_the_ID());
echo '';
}
add_action( 'woocommerce_single_product_summary', 'action_woocommerce_single_product_summary', 5, 0 );

Bước 4: Thêm CSS cho cái hiển thị lượt xem

Quét mã QR để đọc bài viết này để xem tiếp trên điện thoại

QR: Thêm bộ đếm và hiển thị số lượt xem các sản phẩm theme Flatsome không dùng plugin