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.
CodePudding user response:
You'll need to add actions to your functions.php file for WordPress. You can then designate callback functions that return the data you are looking for. PHP code below:
// You add two actions here, so it can be accessed from outside the WP CMS
add_action( 'wp_ajax_project_get_post_count', 'project_get_post_count_callback' );
add_action( 'wp_ajax_nopriv_project_get_post_count', 'project_get_post_count_callback' );
function project_get_post_content_callback() {
if(!empty($_POST['ID'])){
$postID == $_POST['ID'];
$count_key = 'wpb_post_views_count';
$count = get_post_meta($postID, $count_key, true);
$response['views'] = $count;
if($response['views'] ==''){
$response['views'] = 0;
}
wp_send_json( $response );
}
}
Once you have that setup, in javascript you need to do an AJAX post, passing the action name using the action attribute in POST
. This below will get you mostly there. You'll need to format it correctly to be able to get your data. This example is also in jQuery
, vanilla JS will be different. JS code below:
$.ajax({
type: 'POST',
url: ajaxfullurl,
data: {
'action': 'project_get_post_count',
'ID':<YOURIDHERE>
}
});
The last piece you'll need is the AJAX URL (ajaxfullurl
). WordPress provides a way to get that. This is the PHP code that you'll need to extract the URL for AJAX calls on your WordPress website.
echo admin_url('admin-ajax.php');