wordpress - 有没有办法在 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 参数
解决方案
您可以向您的休息路线添加一个名为 的参数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
。
推荐阅读
- mysql - RoR/MySQL 删除 DISTINCT 和 ORDERING 不会产生任何结果
- selenium - 带有 PicoContainer 的 Appium Cucumber 框架的测试数据类 POM
- encryption - 如何从 iOS Swift 中的 RSA 私钥获取模数和指数?
- amazon-web-services - 使用 Python 的 AWS Lambda SES SMTPLib 电子邮件超时
- pytorch - 如何将火炬张量更改为与另一个张量连接
- javascript - 我正在使用 react.js 和 django 作为后端 & 我想使用 axios lib 将图像从 react.js 表单上传到 django
- json - JSON多个别名角8
- c++11 - 我们什么时候应该将 std::unique_ptr 与 std::shared_ptr 用于类成员变量?
- python-3.x - 带有 SAM CLI 的 Lambda 层
- javascript - return 语句在 forEach 循环中不起作用