gpt4 book ai didi

php - 为什么我不能从 WP_REST_Request 访问查询参数?

转载 作者:行者123 更新时间:2023-12-03 19:33:16 24 4
gpt4 key购买 nike

在我的博客上,我正在尝试创建一个端点,以便使用 ajax 加载更多文章。但是,查询字符串参数似乎没有传递给我的函数。
这是我的代码,所有这些都在 function.php 中文件:

add_action( 'rest_api_init', function () {
register_rest_route( 'blog', '/articles', array(
'methods' => WP_REST_Server::READABLE,
'callback' => 'load_more'
));
});

function load_more(WP_REST_Request $request) {
var_dump($request->has_valid_params());
var_dump($request->get_params());
var_dump($request);
}

这是我调用 /wp-json/blog/articles/?lang=en&tag=test 时返回的结果:
bool(true)

array(0) {}

object(WP_REST_Request)#2259 (8) {
["method":protected]=>
string(3) "GET"
["params":protected]=>
array(6) {
["URL"]=>
array(0) {
}
["GET"]=>
array(0) {
}
["POST"]=>
array(0) {
}
["FILES"]=>
array(0) {
}
["JSON"]=>
NULL
["defaults"]=>
array(0) {
}
}
["body":protected]=>
string(0) ""
["route":protected]=>
string(14) "/blog/articles"
["attributes":protected]=>
array(6) {
["methods"]=>
array(1) {
["GET"]=>
bool(true)
}
["accept_json"]=>
bool(false)
["accept_raw"]=>
bool(false)
["show_in_index"]=>
bool(true)
["args"]=>
array(0) {
}
["callback"]=>
string(9) "load_more"
}
["parsed_json":protected]=>
bool(true)
["parsed_body":protected]=>
bool(false)
}

这几乎就像在到达我的函数之前从请求对象中删除了参数。

最佳答案

您可以通过 WP_REST_Request::get_query_params() 访问查询参数:

$queryParams = $request->get_query_params();
$tag = $queryParams['tag'];

或者你可以使用
$tag = $request->get_param('tag');

但合并 $_POST , $_GET和路径参数按该顺序

关于php - 为什么我不能从 WP_REST_Request 访问查询参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52299874/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com