路由的处理程序无效 - Wordpress [英] The handler for the route is invalid - Wordpress

查看:14
本文介绍了路由的处理程序无效 - Wordpress的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用类在 WordPress 中创建自定义 REST API 端点.我也用传统的方式做了同样的事情——效果很好.但是,使用类时出现错误路由的处理程序无效.

I am trying to create a custom REST API endpoint in WordPress using Classes. I've also done the same the traditional way - which worked just fine. However, using classes I am getting an error 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,网站上只有一个帖子,所以应该没有关系.

The query is set to -1, there is only one post on the website so it shouldn't matter.

推荐答案

这里的问题是回调没有到达函数.

The problem here is that the callback is not reaching the function.

解决了以下额外功能的问题:

Solved the issue with the extra function below:

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' );

希望这对未来的人有所帮助:)

Hope this helps someone in future :)

这篇关于路由的处理程序无效 - Wordpress的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆