Show popular post via JSON API plugin

1k Views Asked by At

I am using JSON API plugin to retrieve the post data in json format its working fine.

Now I want to retrieve popular(Most Viewed) posts using same Plugin. How can i achieve this.

1

There are 1 best solutions below

0
On

WordPress doesn't store the number of views for each post so this isn't possible with just the JSON API. You'd need to run a count stored in post_meta on each page load, something like:

function post_view_count() {
    if ( is_single() ) {
        $count = get_post_meta( get_the_ID(), 'post_view_count', true ) ?: 0;
        update_post_meta( get_the_ID(), 'post_view_count', $count++ );
    }
}
add_action( 'wp_head', 'post_view_count' );

Then you can query the API for one post, sorted by the key 'post_view_count' in descending order. You may need to add something like this to allow querying post_meta with the API:

function json_allow_meta_query( $valid_vars ) {
    $valid_vars = array_merge( $valid_vars, array( 'meta_key', 'meta_value', 'meta_compare' ) );
    return $valid_vars;
}
add_filter( 'rest_query_vars', 'json_allow_meta_query' );

However, be aware that you're adding two database hits for EVERY post load which will impact performance.