0

I have registered a rest field in my functions.php for the API to show:

register_rest_field( 'post', 'views', array(
'get_callback' => function ( $data ) {
    return get_post_meta( $data['id'], 'tie_views', true );
}, ));

It is showing the result correctly, now I want a custom endpoint API which I created to sort the result by the number of views from higher to lower from 2 days ago. This is the code:

For the action:

add_action('rest_api_init', function(){

register_rest_route('tft/v1', 'posts/trend/(?P<page>\d+)', array(
    'method' => 'GET',
    'callback' => 'tft_trend'
));

});

and this is the function:

function tft_trend($page){
$args = [
    'post_type' => 'post',
    'posts_per_page' => 5,
    'nopaging' => false,
    'paged' => $page['page'],
    'order' => 'DESC',
    'orderby' => 'tie_views',
    'meta_key' => 'tie_views',
];

$posts = get_posts($args);

$data = [];
$j = 0;

foreach($posts as $post){
    $data[$j]['id'] = $post->ID;
    $data[$j]['title'] = $post->post_title;
    $data[$j]['content'] = $post->post_content;
    $data[$j]['views'] = $post->tie_views;
    $data[$j]['featured_image']['large'] = get_the_post_thumbnail_url($post->ID, 'large');
    $j++;
}
return $data;
}

The function is also working fine but the issue is that it is only taking the number of views and arranging it from 999 and backwards. I have posts which have thousands of views but it is not fetching those results. I would appreciate any help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.