Cập nhật ngày 19/03/2023

Lưu ý: Cách này không dùng Plugin

Bài viết này sẽ hướng dẫn các bạn thêm "Lượt xem" vào bài viết mà không sử dụng plugin, mặc dù có rất nhiều plugin có thể làm việc này!

Lượt xem sẽ được lưu vào Post meta dành cho bạn nào chưa biết.

Đầu tiên hay thêm mã nàu vào file functions.php hoặc site-specific plugin

<?php

const _POST_META_VIEW = 'post_meta_view';

function get_post_meta_view( $postID ): string {
	$count = get_post_meta( $postID, _POST_META_VIEW, true );

	if ( $count == '' ) {
		delete_post_meta( $postID, _POST_META_VIEW );
		add_post_meta( $postID, _POST_META_VIEW, '0' );

		return 0;
	}

	return $count;
}

function set_post_meta_view( $postID ) {
	$count = get_post_meta( $postID, _POST_META_VIEW, true );

	if ( $count == '' ) {
		delete_post_meta( $postID, _POST_META_VIEW );
		add_post_meta( $postID, _POST_META_VIEW, '0' );
	} else {
		$count ++;
		update_post_meta( $postID, _POST_META_VIEW, $count );
	}
}

// Remove issues with prefetching adding extra views
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head' );

// Add to a column in WP-Admin
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() );
	}
}

Tiếp theo là file single.php, hãy đặt vào Wordpress Loop (sau the_post())

Đoạn nãy sẽ tự động cộng lượt xem

<?php set_post_meta_view(get_the_ID()) ?>

Đoạn này để hiện lượt xem

<?php echo get_post_meta_view(get_the_ID()) ?>