WordPress WC_Integration类内register_rest_route注册接口返回404问题
问题根因
- 核心是PHP匿名函数的变量作用域问题:你在
__construct方法内定义的$namespace和$endpoint两个局部变量,没有导入到rest_api_init绑定的匿名函数作用域内,导致register_rest_route执行时拿到的是两个空值,实际注册的路由不符合预期,因此访问时返回404。 - 你看到debug日志正常输出,只能证明
rest_api_init钩子触发、匿名函数执行了,但不代表路由参数是正确的。
修复方案
给匿名函数增加use关键字导入外部需要的变量即可,修改后的代码如下:
class WC_FastSpring_Fulfillment_Integration extends WC_Integration { public function __construct() { $this->id = 'av-wc-fastspring'; $this->method_title = ''; $this->method_description = ''; // Method with all the options fields $this->init_form_fields(); // Load the settings. $this->init_settings(); // This action hook saves the settings add_action( 'woocommerce_update_options_integration_' . $this->id, array( $this, 'process_admin_options' ) ); $namespace = 'test'; $endpoint = '/fs-fulfill-order'; // 仅需修改这一行,新增use导入两个变量 add_action( 'rest_api_init', function () use ($namespace, $endpoint) { $logger = wc_get_logger(); $logger->debug("Registered API Endpoint"); register_rest_route( $namespace, $endpoint, array( 'methods' => 'GET', 'callback' => array($this, 'fulfill_fastspring_order'), 'permission_callback' => function() { return true; } ) ); } ); } public function fulfill_fastspring_order() { global $woocommerce; $logger = wc_get_logger(); $logger->debug("Received request to fullfill FastSpring order via Rest API."); return new WP_REST_Response('Damn !'); } ... }
验证方法
修复后可以先访问站点REST API根路径/wp-json,在返回的路由列表中搜索test/fs-fulfill-order确认路由已注册,再直接访问接口地址/wp-json/test/fs-fulfill-order验证返回结果即可。
内容的提问来源于stack exchange,提问作者Tuft
相关产品推荐
相关产品推荐

