How can I count post views of my WordPress posts when click on a button using AJAX?
Currently it's counting the post view whenever I refresh the page, I want to call tha funtion with ajax.
Please check the code I am currently using to show post view count
Inside the functions.php
if ( ! function_exists( 'count_views' ) ) :
// Get the value of view
function count_views($postID) {
$count_key = 'wpb_post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count ==''){
$count = 1;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '1');
} else {
$count++;
update_post_meta($postID, $count_key, $count);
}
}
endif;
Then on single.php I have called the funtion count_views with get_the_ID();
<?php count_views(get_the_ID()); ?>
To retrieve the view count I have used:
<li>
<i class="fa fa-eye"></i>
<?php
if (get_post_meta(get_the_ID(), 'wpb_post_views_count', true) == '') {
echo '0';
} else {
echo get_post_meta(get_the_ID(), 'wpb_post_views_count', true);
};
?>
</li>
How can I call the count_views(get_the_ID()) funtion using javascript Ajax call.