我想为wordpress站点创建一个REST API端点,在这里我可以获得不同查询的JSON响应。我已经试过了教程here, 但我似乎无法理解它是如何工作的。我是否需要注册所有查询变量才能使用它们?此外,我认为最好使用add_rewrite_endpoint
但我以前从未使用过这些。因此,我想知道如何在下面的代码中使用该函数。
我想发送如下查询<url>/wp-api/version
它将返回wordpress版本号。但现在除了“哈巴狗”之外,它不接受任何查询。我不确定正则表达式到底是怎么回事,所以我没有改变它。有人能帮我理解这一点吗?
class WP_API_Endpoint{
// Hook WordPress
public function __construct(){
add_filter(\'query_vars\', array($this, \'add_query_vars\'), 0);
add_action(\'parse_request\', array($this, \'sniff_requests\'), 0);
add_action(\'init\', array($this, \'add_endpoint\'), 0);
}
/*
Add public query vars
@param array $vars List of current public query vars
@return array $vars
*/
public function add_query_vars($vars){
$vars[] = \'__wp-api\';
$vars[] = \'pugs\';
return $vars;
}
// Add API Endpoint
public function add_endpoint(){
add_rewrite_rule(\'^wp-api/pugs/?([0-9]+)?/?\',\'index.php?__wp-api=1&pugs=$matches[1]\',\'top\');
}
/*
Sniff Requests
This is where we hijack all API requests
If $_GET[\'__api\'] is set, we kill WP and serve our data
@return die if API request
*/
public function sniff_requests(){
global $wp;
if(isset($wp->query_vars[\'__wp-api\'])){
$this->handle_request();
exit;
}
}
protected function get_wp_version() {
return get_bloginfo(\'version\');
}
// This is where we handle incoming requests
protected function handle_request(){
global $wp;
$pugs = $wp->query_vars[\'pugs\'];
if($pugs)
$this->send_response(\'wp-version\', $this->get_wp_version());
else
$this->send_response(\'Something went wrong with the pug bomb factory\');
}
// This sends a JSON response to the browser
protected function send_response($key, $val){
$response[$key] = $val;
header(\'content-type: application/json; charset=utf-8\');
echo json_encode($response)."\\n";
exit;
}
}
new WP_API_Endpoint();
SO网友:Shazzad
首先是添加重写规则函数。你有-
add_rewrite_rule(\'^wp-api/pugs/?([0-9]+)?/?\',\'index.php?__wp-api=1&pugs=$matches[1]\',\'top\');
wp-api/pugs/?([0-9]+)
这意味着,当你要求
<url>/wp-api/pugs/123
, 您将获得一个带有参数的查询变量pugs
123.
$var = get_query_var(\'pugs\'); // = 123
现在,你真的不需要
pugs 根据需要在url中输入。所以,就这样移除它。此外,匹配的正则表达式不应仅为数字。所以更改后的代码是-
add_rewrite_rule(\'^wp-api/?([^/]+)?/?\',\'index.php?__wp-api=1&pugs=$matches[1]\',\'top\');
最终用途是:
protected function handle_request(){
global $wp;
$pugs = $wp->query_vars[\'pugs\'];
// <url>/wp-api/version/
if( \'version\' == $pugs )
$this->send_response( \'wp-version\', $this->get_wp_version() );
// <url>/wp-api/something/
elseif( \'something\' == $pugs )
$this->send_response( \'something\', \'something\' );
else
$this->send_response( \'Something went wrong with the pug bomb factory\');
}