Skip to content

Instantly share code, notes, and snippets.

@csymlstd
Created November 12, 2019 21:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save csymlstd/a1121d0711276c6cdd91456ff3e38ed7 to your computer and use it in GitHub Desktop.
Save csymlstd/a1121d0711276c6cdd91456ff3e38ed7 to your computer and use it in GitHub Desktop.
wp ajax route to increment post view count
<?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