首页 > 解决方案 > 有没有办法在 WordPress 中获取相关帖子 API?

问题描述

我需要创建一个 API,它将按类别过滤器呈现相关帖子。我已经在我的 functions.php 文件中编写了代码,但我没有明白如何将帖子 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 参数

我需要从中呈现相关 API 的当前帖子 API 的图像 我需要从中呈现相关 API 的当前帖子 API

标签: wordpresswordpress-rest-api

解决方案


您可以向您的休息路线添加一个名为 的参数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


推荐阅读