有没有办法在 WordPress 中获取相关帖子 API?

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

我需要创建一个 API 来呈现相关的 post 按类别筛选。我已经在 functions.php 文件中编写了代码,但我不知道如何将 post id 传递给参数?

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'
    ) );
} );

我需要传递我当前 API 调用的 ID。因此,我需要将该 id 传递给我当前作为静态 (180)

传递的相关 API 参数

当前 post API 的图像,我需要从中渲染相关 API

您可以像普通的 get 请求一样获取 post id。 ?key=value 并使用它的广告 $request['key'] 所以你的代码应该是这样的。

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'
    ));
});

现在你的apiurl应该是这样的/post/related?post_id=183 试试这个然后让我知道结果。

您可以向您的休息路由添加一个名为 post_id 的参数,然后从 request_data 数组中访问该 ID。

function related_posts_endpoint( $request_data ) {

    $post_id = $request_data['post_id'];

    $uposts = get_posts(
        array(
            'post_type' => 'post',
            'category__in'   => wp_get_post_categories($post_id),
            'posts_per_page' => 5,
            'post__not_in'   => array($post_id),
        )
    );

    return  $uposts;
}

add_action( 'rest_api_init', function () {

    register_rest_route( 'sections/v1', '/post/related/(?P<post_id>[\d]+)', array(
            'methods' => 'GET',
            'callback' => 'related_posts_endpoint'
    ));

});

您可以将 ID 添加到 URL 调用的末尾 /post/related/183