white printer paper on a vintage typewriter

Showing Post View Count in WordPress Block Theme

in

— 15 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.

The Bioinformatics Newsletter

I often explore new tools and techniques for various bioinformatics analyses. Often these adventures yield no results. But sometimes they are fruitful, and I incorporate them into my project workflows.

My proposal to you is that I will write sporadic newsletters. The main content of this newsletter will be my experiments: what tool I explored, what worked, how it worked, and why I am using it, etc.

Do you think you would like to read these monologues? If this is something that resonates with you, please subscribe. 🙂

Join 95 other subscribers

Comments

Leave a Reply