white printer paper on a vintage typewriter

Showing Post View Count in WordPress Block Theme

in

— 8 reads

In 2023, WordPress released block themes where the single.php code is gone, which is generally used to render single post pages. I have recently experimented with these block themes. You just use the block theme editor within the site, add different blocks by drag-and-drop, and use different patterns, etc. This totally changes the game. I have found the new “block” themes are really cool and super fast as well.

I needed to show Jetpack view count for each posts in another website. Earlier, I used to add a function and change the single.php file. But since there is no single.php file now, I have to add the following code in the functions.php file.

I find WordPress post view count relatively conservative and more trustworthy.

This PHP code gets the page views for a particular post and parses it through a shortcode.

Add the following code in your functions.php file. This defines the get_page_views function and create a short-code for it.

function get_page_views() {
    $post_id = get_the_ID(); 
	if (function_exists('stats_get_csv')) {
	
		$args = array('days'=>-1, 'limit'=>-1, 'post_id'=>$post_id);
		$result = stats_get_csv('postviews', $args);
		$views = $result[0]['views'];

	} else {

		$views = 0;

	}
	return number_format_i18n($views);
}


add_shortcode("show-jetpack-counter","get_page_views");

You just need to insert the short-code [show-jetpack-counter] into a block on your post page template. You can add that in the post meta or elsewhere.


Comments

Leave a Reply

Join as a subscriber

Only the posts on data visualization, bioinformatics how to tutorials, web-development, and general comments on research and science will be sent.

Join 10 other subscribers