wordpress - 路由的处理程序无效 - Wordpress
问题描述
我正在尝试使用类在 WordPress 中创建自定义 REST API 端点。我也用传统的方式做了同样的事情——效果很好。但是,使用类我得到一个错误The handler for the route is invalid
。
编码:
class CSS_Ads {
var $url;
var $endpointPrefix;
var $endpointName;
public function __construct()
{
add_action('rest_api_init', array( $this, 'ads_api_route' ) );
}
public function ads_api_route() {
register_rest_route( $this->endpointPrefix, $this->endpointName,
array(
'methods' => 'GET',
'callback' => 'get_all_ads_api_endpoint'
)
);
}
public function get_all_ads_api_endpoint($params) {
// doing my post query and stuff
}
}
环境:
$ads = new CSS_Ads();
$ads->url = get_site_url();
$ads->endpointPrefix = 'bs/v1';
$ads->endpointName = 'ads';
完整错误:
{"code":"rest_invalid_handler","message":"The handler for the route is invalid","data":{"status":500}}
查询设置为-1,网站上只有一个帖子,所以没关系。
解决方案
这里的问题是回调没有到达函数。
解决了以下额外功能的问题:
public function __construct()
{
// Add custom REST API endpoint
add_action('rest_api_init', __NAMESPACE__ . '\\ads_api_route' );
}
// REST API route
public function ads_api_route() {
register_rest_route( 'my_endpoint/v1', '/ads',
array(
'methods' => 'GET',
'callback' => [$this, 'get_all_ads_api_endpoint']
)
);
}
function init_rest_api_endpoint() {
$endpoint = new restAPIendpoint();
$endpoint->ads_api_route();
}
add_action( 'rest_api_init', 'init_rest_api_endpoint' );
希望这对将来的人有所帮助:)
推荐阅读
- javascript - 如何使用 Javascript Regex 使用该单词中的一个字符拆分单词?
- reactjs - 如何渲染 [对象 SVGSVGElement]
- android - 如何在android xml字符串资源中获取标签
- android - 在视图初始化时触发自身的所有 UI 组件(视图)中添加附加功能
- docker - 使用 docker engine api 加载 docker 镜像
- javascript - 使用没有包管理器的 Polymer Web 组件
- python - 如何用另一个数据框的一行的下一个元素填充数据框?
- php - 付款前如何在结帐页面获取订单ID
- javascript - 使用 $(document).ready() 和 $.getScript() 在页面加载完成后加载外部脚本
- php - 翻译器未加载正确的语言环境