A lightweight plugin that works immediately after activation without any configuration. It counts views for posts, supports Custom Post Types, and is based on this code. In the admin panel, a column showing the number of views is added to the page with all posts.

All statistics are stored in custom fields and are accessible through the standard function get_post_meta. Views from logged-in users and well-known search engine bots are not included in the statistics.

To display the number of post views, you need to insert this code in the appropriate place in the page template:

<?php echo get_post_meta( $post->ID, 'views', true ); ?>

The plugin also stores the time of the last view in the post’s custom fields. Based on this data, you can display a list of the most recently viewed posts on the site.

Code to get the last 5 viewed posts:


$posts = get_posts( [
	'numberposts'	=> 5,
	'post_status'	=> 'publish',
	'meta_query' 	=> array (
		'lastview' 	=> array(
			'key' 			=> 'lastview',
			'value_num' 	=> 0,
			'type'    		=> 'numeric',
			'compare' 		=> '>'
		)
	),
	'orderby' 		=> 'lastview',
	'order'   		=> 'DESC',
] );

Then, the $posts variable is processed as an array to extract all necessary data for generating the list of recently viewed posts.

Share: