Code hiển thị lượt xem bài viết trong theme Flatsome – không cần dùng plugin

Lượt xem: 10

Hiển thị số lượt xem bài viết trong WordPress giúp chúng ta đánh giá tốt hơn về phản ứng của khách hàng với nội dung bài viết. Các bạn có thể dùng các Plugin có sẵn để giải quyết nhanh vấn đề này. Tuy nhiên nếu bạn rành về code và muốn tối ưu hơn cho website của mình thì có thể tham khảo các đoạn code mình sưu tập sau đây để đếm view, hiển thị cho các bài viết (post) và sản phẩm (product) trong web mình nhé.

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

Thêm các đoạn code sau vào Function.php trong child-theme nhé.

Bước 1: 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';
}

Bước 2: 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);
    }
}

Bước 3: 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());
    }
}

2. Viết code hiển thị lượt xem

Các đoạn code trên chỉ mới đếm và lưu các lượt xem vào data thôi chứ chưa hiển thị, thêm các đoạn code sau vào file tương ứng để xem thành quả của mình nhé:

Thêm code hiển thị lượt xem trong trang

Các bạn thêm đoạn code dưới đây   setPostViews(get_the_ID()); vào bất kỳ vị trí nào trong code của post. Cách tốt nhất là hook vào header của Flatsome bằng hàm như bên dưới vào function.php của theme.

function hwp_count(){
if ( is_single() ) :
setPostViews(get_the_ID());
endif;
}
add_action( 'flatsome_after_header', 'hwp_count' );

Thêm code hiển thị lượt xem trong trang

Code hiển thị các thông số view ta hook vào title của post bằng cách overwrite hàm sau của theme Flatsome nhé

function flatsome_posted_on() {
    $time_string = '<time class="entry-date published updated" datetime="%1$s">%2$s</time>';
    if ( get_the_time( 'U' ) !== get_the_modified_time( 'U' ) ) {
        $time_string = '<time class="entry-date published" datetime="%1$s">%2$s</time><time class="updated" datetime="%3$s">%4$s</time>';
    }

    $time_string = sprintf( $time_string,
        esc_attr( get_the_date( 'c' ) ),
        esc_html( get_the_date() ),
        esc_attr( get_the_modified_date( 'c' ) ),
        esc_html( get_the_modified_date() )
    );

    $posted_on = sprintf(
        esc_html_x( 'Posted on %s', 'post date', 'flatsome' ),
        '<a href="' . esc_url( get_permalink() ) . '" rel="bookmark">' . $time_string . '</a>'
    );

    $byline = sprintf(
        esc_html_x( 'by %s', 'post author', 'flatsome' ),
        '<span class="meta-author vcard"><a class="url fn n" href="' . esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ) . '">' . esc_html( get_the_author() ) . '</a></span>'
    );
	
	echo 
	'<div class = "tp-post-meta">
		<span class="posted-on"><i class="fa fa-address-book-o" aria-hidden="true"> </i>' . $posted_on . '|</span>  
		<span class="byline"><i class="fa fa-user-o" aria-hidden="true"> </i>' . $byline . '|</span>  
		<span class="tp-post-view"><i class="fa fa-eye" aria-hidden="true"> </i>'.getPostViews(get_the_ID()).'|</span>  

	</div>';

}

Viết widget hiển thị bài xem nhiều

Các bạn thêm đoạn code sau vào function.php của theme nhé.

function create_topview_widget() {
    register_widget( 'TopView_Widget' );
}
add_action( 'widgets_init', 'create_topview_widget' );
 
class TopView_Widget extends WP_Widget {
 
    
     //Thiết lập tên widget và description của nó (Appearance -> Widgets)
    function __construct() {
        $options = array(
           'classname' => 'topview',
            'description' => 'Xem bài viết xem nhiều nhất'
        );
        $this->WP_Widget('topview', 'Top View', $options);
    }
 
    //Tạo form điền tham số cho widget
    //ở đây ta có 3 form là title, postnum (số lượng bài) và postdate (tuổi của bài
    
    function form($instance) {
        $default = array(
            'title' => 'Bài xem nhiều nhất',
            'postnum' => 5,
            'postdate' => 30
        );
        $instance = wp_parse_args( (array) $instance, $default );
        $title = esc_attr( $instance['title'] );
        $postnum = esc_attr( $instance['postnum'] );
        $postdate = esc_attr( $instance['postdate'] );
 
        echo "<label>Tiêu đề:</label> <input class='widefat' type='text' name='".$this->get_field_name('title')."' value='".$title."' />";
        echo "<label>Số lượng bài viết:</label> <input class='widefat' type='number' name='".$this->get_field_name('postnum')."' value='".$postnum."' />";
        echo "<label>Độ tuổi của bài viết (ngày)</label> <input class='widefat' type='number' name='".$this->get_field_name('postdate')."' value='".$postdate."' />";
    }
 
    //Cập nhật dữ liệu nhập vào form tùy chọn trong database   
    function update($new_instance, $old_instance) {
        $instance = $old_instance;
        $instance['title'] = strip_tags($new_instance['title']);
        $instance['postnum'] = strip_tags($new_instance['postnum']);
        $instance['postdate'] = strip_tags($new_instance['postdate']);
        return $instance;
    }
 
    function widget($args, $instance) {
        global $postdate; // Thiết lập biến $postdate là biến toàn cục để dùng ở hàm filter_where
        extract( $args );
        $title = apply_filters( 'widget_title', $instance['title'] );
        $postnum = $instance['postnum'];
        $postdate = $instance['postdate'];
 
        echo $before_widget;
        echo $before_title.$title.$after_title;
 
        $query_args = array(
            'posts_per_page' => $postnum,
            'meta_key' => 'post_views_count', //post_views_count postview_number
            'orderby' => 'meta_value_num',
            'order' => 'DESC',
            'ignore_sticky_posts' => -1
        );
 
        //Cách lấy bài viết theo độ tuổi (-30 days = lấy bài được 30 ngày tuổi)
        function filter_where( $where = '' ) {
            global $postdate;
            $where .= " AND post_date > '" . date('Y-m-d', strtotime('-'.$postdate.' days')) . "'";
            return $where;
        }
        add_filter( 'posts_where', 'filter_where' );
 
        $postview_query = new WP_Query( $query_args );
 
        remove_filter( 'posts_where', 'filter_where' ); // Xóa filter để tránh ảnh hưởng đến query khác
 
        if ($postview_query->have_posts() ) :
            echo "<ul>";
            while ( $postview_query->have_posts() ) :
                $postview_query->the_post(); ?>
 
                    <li>

						
						<div class="flex-row pt-half pb-half">
							<div class="flex-col mr-half">
								<div class="badge post-date  badge-circle-inside">
									<?php 
										if ( has_post_thumbnail() ) the_post_thumbnail(array(92,69)); 
										else echo "</br><img src='/wp-content/themes/codfe-theme/images/noimage.png'>";
									?>
								</div>
							</div><!-- .flex-col -->
							<div class="flex-col flex-grow">
								<a href="<?php the_permalink(); ?>">
									<?php 
										the_title(); echo " | <i>".getPostViews(get_the_ID())."</i>";
									?>
								</a>
							</div>
						</div><!-- .flex-row -->
						
						
                    </li>
 
            <?php endwhile;
            echo "</ul>";
            endif;
            echo $after_widget;
    }
}

Hiển thị lượt xem trong trang sản phẩm

Dùng đoạn code như sau để hiển thị lược xem trong trang sản phẩm Flatsome

add_action( 'woocommerce_product_meta_start','codfe_show_post_view' );
function hwp_show_post_view(){
	//echo current_filter().'</br>';
	echo 
	'<div class = "tp-post-meta">
		<span class="post-views"><i class="fa fa-eye"></i>'.getPostViews(get_the_ID()).'</span>
	</div>';	
}

add_shortcode("hwp-show-product-views","hwp_show_post_view");

Trong đoạn code trên có tạo shortcode là [ hwp-show-product-views] để hiển thị views, các bạn có thể thêm shortcode này vào bất kỳ đâu trong bài viết để hiển thị ra nhé.

Các bạn xem thêm các bài viết sau để chọn lại vị trí hiển thị phù hợp với mình nhé!

Chúc bạn thành công

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *

0393.090.491