Search code examples
wordpresswordpress-rest-api

Is there any way to get related posts API in WordPress?


I need to create an API that will render a related post by category filter. I have written the code in my functions.php file but I did not get how can I pass a post id to the arguments?

function related_posts_endpoint( $request_data ) {
    $uposts = get_posts(
    array(
        'post_type' => 'post',
        'category__in'   => wp_get_post_categories(183),
        'posts_per_page' => 5,
        'post__not_in'   => array(183),
    ) );
    return  $uposts;
}

add_action( 'rest_api_init', function () {
    register_rest_route( 'sections/v1', '/post/related/', array(
        'methods' => 'GET',
        'callback' => 'related_posts_endpoint'
    ) );
} );

I need to pass the id from my current API call. So, I need to pass that id to the related API arguments that I have currently passed as static (180)

Image of Current post API from which I need to render a related API Current post API from which I need to render a related API


Solution

  • Your can get the post id like normal get request. ?key=value and use its ad $request['key'] so Your code should be like this.

    function related_posts_endpoint( $request_data ) {
        $uposts = get_posts(
        array(
            'post_type' => 'post',
            'category__in'   => wp_get_post_categories(183),
            'posts_per_page' => 5,
            'post__not_in'   => array($request_data['post_id']),//your requested post id 
        )
        );
        return  $uposts;
     }
    add_action( 'rest_api_init', function () {
        register_rest_route( 'sections/v1', '/post/related/', array(
                'methods' => 'GET',
                'callback' => 'related_posts_endpoint'
        ));
    });
    

    Now your api url should be like this /post/related?post_id=183 try this then let me know the result.