WordPress get and set page visit count

Try Fast Read

WordPress is one of the most widely used cms across the world of php and web development. It can serve you with simple blogs, to a more complex website and also e-commerce. It has lots of features build it and rest can be modified via functions.php. Lets look at how does wordpress get and set page visit count work.

Usually we need get most popular or most visited page/post in wordpress, this can be done easily by adding two functions in functions.php

The following function is used to insert/increase page view count everytime a page is visited.

function wpb_set_post_views($postID) {
	$count_key = 'wpb_post_views_count';
	$count = get_post_meta($postID, $count_key, true);
		$count = 0;
		delete_post_meta($postID, $count_key);
		add_post_meta($postID, $count_key, '0');
		update_post_meta($postID, $count_key, $count);
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);

you can now set the view count by calling  wpb_set_post_views(get_the_ID()); inside the template
function wpb_track_post_views ($post_id) {
	if ( !is_single() ) return;
	if ( empty ( $post_id) ) {
		global $post;
		$post_id = $post->ID;    
add_action( 'wp_head', 'wpb_track_post_views');

you can now get the view count by calling  wpb_get_post_views(get_the_ID()); inside the template

You can also use this in query, to get most popular/most viewed page/post

$popularpost = new WP_Query( array( 'posts_per_page' => 4, 'meta_key' => 'wpb_post_views_count', 'orderby' => 'meta_value_num', 'order' => 'DESC'  ) );
while ( $popularpost->have_posts() ) : $popularpost->the_post();



Note: If you are using a caching plugin, this technique will not work by default. If you are using W3 Total Cache, you can usea feature called Fragmented Caching to make this work just fine. For that just set view count using the following

< !-- mfunc wpb_set_post_views($post_id); -->< !-- /mfunc -->

Credit: wpbeginner.com

Post navigation