How can I filter the most popular post from my Wordpress blog using the WP Rest API and Post views counter plugin?

231 Views Asked by At

I'm using the Wordpress as a CMS and I'm trying to filtering the most popular post of my wordpress blog using the plugin "Post views counter" and "WP Rest API". I already have 3 functions that creates a field on my endpoint which the name is "post_views" and it's already showing the number of views on each post. My problem is to filter the most popular post (with most views). When I make a HTTP GET with the url "http://localhost:8000/wp-json/wp/v2/posts?order_by=post_views&order=desc" its returning me a empty array with no posts in it. Does somebody know how can I make this filter?

Functions to create the field (that is working fine):

function add_post_views_to_rest_api() {

    if (class_exists('Post_Views_Counter')) {

        register_rest_field('post', 'post_views', array(
            'get_callback' => 'get_post_views_count',
            'schema' => null,
        ));
    }
}

add_action('rest_api_init', add_post_views_to_rest_api');


function get_post_views_count($object) {
    $post_id = $object['id'];

    if (class_exists('Post_Views_Counter')) {

        $views_count = pvc_get_post_views($post_id);

        return intval($views_count);
    }

    return 0;
}

I already tried to add this function to filter the posts:

Function thats filter by "order_by" (or it is supposed to):

function custom_posts_query($args) {
    $orderby = isset($_GET['order_by']) ? $_GET['order_by'] : '';

    if ($orderby === 'post_views') {
        $args['meta_key'] = 'post_views';
        $args['order_by'] = 'meta_value_num';
    }

    return $args;
}
add_filter('rest_post_query', 'custom_posts_query');
0

There are 0 best solutions below