For further reference if someone needs to do the same :
function increment_view_AJAX_script() {
$ajax_nonce = wp_create_nonce('increment_post_view_nonce');
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
// Trigger action only when ajax loads page use PJAX or any other triggers your system uses to load page without browser reload
$(document).on('pjax:complete', function() {
// find the ID in the template. Here it is in <main id="main"><article id="post-123">...</article></main>
var mainElement = document.getElementById('main');
var articleElement = mainElement.querySelector('article');
if (articleElement) {
var postIDFull = articleElement.getAttribute('id');
if (postIDFull && postIDFull.startsWith('post-')) {
// Extract post ID from ID attribute (ex: post-643)
var postIDNumber = postIDFull.substring('post-'.length);
var postID = parseInt(postIDNumber, 10);
// Call AJAX action to increase post views
$.ajax({
url: <?php echo json_encode(admin_url('admin-ajax.php')); ?>,
type: 'POST',
data: {
action: 'increment_post_view',
post_id: postID,
nonce: '<?php echo $ajax_nonce; ?>',
},
success: function(response) {
}
});
}
}
});
});
</script>
<?php
}
add_action('wp_footer', 'increment_view_AJAX_script', 500);
/**
* Ajax action callback that increases view on a post
*/
function litt_increment_post_view_callback() {
if ( isset($_POST['nonce']) && wp_verify_nonce($_POST['nonce'], 'increment_post_view_nonce') ) {
if (isset($_POST['post_id'])) {
$post_id = intval($_POST['post_id']);
pvc_view_post( $post_id );
}
}
die();
}
add_action('wp_ajax_increment_post_view', 'litt_increment_post_view_callback');
add_action('wp_ajax_nopriv_increment_post_view', 'litt_increment_post_view_callback');
-
This reply was modified 1 year, 3 months ago by julianoe.