How-to count AMP views in Wordpress

how to count amp views in wordpress


Recently I was involved in a project, more details later. The website had a theme which I re-coded from scratch and I've implemented an AJAX views count as there were issues in the past with views not counted due to the cache system.

 

This solution works very good. Ths issue is that after Google re-indexed everything, around 70-80% of the views are now from AMP pages. I'm using official AMP plugin. AMP pages are loaded from Google cache and don't run "classic" Javascript. That's why the views for articles were not counting the AMP views but only the views from non-AMP pages.

 

The solution is to use an AMP pixel which can send a request with the post_id so we can update the views in the database. This applies for AMP pages served from the hosting server and also for the pages from Google cache.

 

To "inject" the AMP pixel we need to add the below code to functions.php (AMP plugin documentation):

 

add_action( 'amp_post_template_footer', 'xyz_amp_add_pixel' );
function xyz_amp_add_pixel( $amp_template ) {
$post_id = $amp_template->get( 'post_id' );
?>
<amp-pixel src="https://yourdomain.tld/fisierul_de_update.php?post_id=<?php echo $post_id; ?>"></amp-pixel>
<?php
}

 

We can check if the request is made by looking into Developer tools - Network tab.

 

fisierul_de_update.php can have any filename but be sure that you'll update the pixel src filename also. Inside this file we use the post_id with GET, sanitize it then we can run the query to update the views for that post_id in the database.