我在设置路由注册函数时遇到问题,直到我记得向其中添加名称空间:
add_action(\'rest_api_init\', \'\\DelayedCoupons\\registerDummyRoute\');
但现在我相信我在课堂上遇到了同样的问题,我似乎无法解决它。下面我犯了什么错误?
// main file
namespace DelayedCoupons;
require_once (\'adminSettingsArea/ApiController.php\');
use \\admin\\controllers\\ApiController;
$apiController = new ApiController();
add_action(\'rest_api_init\', [$apiController, \'registerDummyResponse\']);
// class file required above
namespace admin\\controllers;
class ApiController extends \\WP_Rest_Controller {
protected $namespace = \'delayedCoupons\';
protected $version = \'1.0\';
protected $urlBase;
public function __construct() {
$this->urlBase = $this->namespace . \'/\' . $this->version;
}
protected function respondWithString() {
wp_send_json(\'dummy response\');
}
public function registerDummyResponse() {
register_rest_route($this->urlBase, \'dummy\', [
\'methods\' => \'GET\',
// \'callback\' => \'\\admin\\controllers\\ApiController\\respondWithString\'
// \'callback\' => \'ApiController\\respondWithString\'
\'callback\' => \'respondWithString\'
]);
}
最合适的回答,由SO网友:Sally CJ 整理而成
回调必须是公共的:
public function respondWithString()
在你的
register_rest_route()
呼叫,设置
callback
到
[ $this, \'respondWithString\' ]
:
register_rest_route( $this->urlBase, \'dummy\', [
\'methods\' => \'GET\',
\'callback\' => [ $this, \'respondWithString\' ],
] );