Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save cabrerahector/62c667e9316b1fd1792eea338721b354 to your computer and use it in GitHub Desktop.
Save cabrerahector/62c667e9316b1fd1792eea338721b354 to your computer and use it in GitHub Desktop.
WordPress Popular Posts - Prevent Users from Inflating Views Count
<?php
/**
* Prevent users from inflating the views count of a post
* or page by repeatedly hitting F5 / browser's refresh key.
*/
function wpp_maybe_skip_pageview_tracking() {
if ( is_singular() ) {
?>
<script>
(function() {
const today = new Date(),
post_id = <?php echo (int) get_queried_object_id() ?>,
storage = localStorage.getItem('wpp_views'),
currDate = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate(),
defaults = {
date: currDate,
viewed: [post_id]
};
let data = null;
if ( storage ) {
data = JSON.parse(storage);
const storedDate = data.date;
/** Views data is still current, should we track this pageview? */
if ( currDate == storedDate ) {
/** Post hasn't been tracked yet */
if ( ! data.viewed.includes(post_id) ) {
data.viewed.push(post_id);
}
/** Post already tracked today, bail */
else {
window.wpp_do_request = false;
}
}
/** Old views data, reset */
else {
data = defaults;
}
}
/** No views data yet */
else {
data = defaults;
}
localStorage.setItem('wpp_views', JSON.stringify(data));
})();
</script>
<?php
}
}
add_action('wp_head', 'wpp_maybe_skip_pageview_tracking', 1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment