// 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');