view counter update in WordPress REST api HTTP get

I use WordPress rest API for app communication with my site in need update post view counter when HTTP get API.

I search a lot but nothing found about it, in a tutorial "Find popular posts with the WordPress REST API" view counter update when call HTTP get API URL but it's in custom endpoint but I need this update function in rest API default endpoint

the code for popular post custom endpoint :

add_action( 'rest_api_init', function () {
  register_rest_route( 'base', '/views/(?Pid\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;
  }
}

how I change and use for my purpose?

in default get rest API URL is: "http://www.test.com/wp-json/wp/v2/posts/id". there is a custom field for view counter. when using Get Request rest API URL of a post, view field increase

thank a million

Topic wp-remote-request rest-api views Wordpress

Category Web

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.