John Davidson

php - WordPress Function to Add Page Views to API

0 comments
Message:


Good day WordPress developers


I have searched the internet looking for a WordPress Function that adds views from Jetpack from post endpoint. I am really finding it difficult because I am not a WordPress or PHP developer. I am only using it as my backend.


Alternatively, if I can create my own function that increases when a request is made I will love it.


Below is what I found from the internet but it didn't work for me.


function getPostViews($postID){
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
return "0 View";
}
return $count.' Views';

}



My Answer:
0;
}else{
$count++;
update_post_meta($postID, $count_key, $count);
return $count;
}
}

You can use this function in your WordPress theme or plugin to get and increment the post views count. Just pass the post ID as a parameter to the function.

Alternatively, you can use the Jetpack API to get the post views count. Here is an example code snippet to get the post views count using the Jetpack API:

function get_jetpack_post_views($postID){
$stats = stats_get_from_restapi( 'postviews', 'v1', 'postviews', $postID );
return $stats['data']['views'];
}

You can use this function to get the post views count from the Jetpack API. Just pass the post ID as a parameter to the function.

I hope this helps! Let me know if you have any further questions.

Rate this post

3 of 5 based on 3621 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us