i have some custom post meta for counting view,
image of api (http://www.test.com/wp-json/wp/v2/posts)
i need update (increase ++) post view counter when i get "http://www.test.com/wp-json/wp/v2/posts/1234" (1234 is post id)
i search a lot but i don't find any thing, although i fine this code :
add_action( 'rest_api_init', function () {
register_rest_route( 'base', '/views/(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => 'post_view_counter_function',
));
});
function post_view_counter_function( WP_REST_Request $request ) {
$post_id = $request['id'];
if ( FALSE === get_post_status( $post_id ) ) {
return new WP_Error( 'error_no_post', 'Not a post id', array( 'status' => 404 ) );
} else {
$current_views = get_post_meta( $post_id, 'views', true );
$views = $current_views + 1;
update_post_meta( $post_id, 'views', $views );
return $views;
}
}
BUT the problem of above code is being separate and custom endpoint, i need increase view counter (cd_plays in image) by every html get request the post api (http://www.test.com/wp-json/wp/v2/posts/1234)
please give me a guide, i stuck about this
In this code many changes 1. register_rest_route( 'base', '/views/(?P\d+)', array(
Change to register_rest_route( 'base/v1', if you want no major changes so this url , http://www.test.com/wp-json/base/v1/views/1234
You can also limit the posts per page you're fetching to 1 so you're not getting all your WordPress posts just to get the posts to count.
http://demo.wp-api.org/wp-json/wp/v2/posts?per_page=1
Thanks