Created
November 12, 2019 21:14
-
-
Save csymlstd/a1121d0711276c6cdd91456ff3e38ed7 to your computer and use it in GitHub Desktop.
wp ajax route to increment post view count
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function get_post_count($id = null) { | |
if($id == null) return; | |
$key = 'post_views_count'; | |
$count = get_post_meta($id, $key, true); | |
if($count == '') { | |
$count = 0; | |
delete_post_meta($id, $key); | |
add_post_meta($id, $key, $count); | |
} | |
return $count; | |
} | |
function set_post_count($id = null, $count = 0) { | |
if($id == null) return; | |
$key = 'post_views_count'; | |
$count = get_post_count($id); | |
$count++; | |
update_post_meta($id, $key, $count); | |
} | |
function adaptable_post_view_increase( WP_REST_Request $request ) { | |
$id = (int) $request['id']; | |
set_post_count($id); | |
return; | |
} | |
add_action('rest_api_init', function () { | |
register_rest_route( 'adaptable', '/view/(?P<id>\d+)', array( | |
'methods' => 'POST', | |
'callback' => 'adaptable_post_view_increase', | |
)); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment