该文件仅覆盖适用于模板的 AFAIK。在本例中,您尝试重写一个不同的类。
正如您所写,直接对 WooCommerce 目录中的文件进行更改并不是一个好主意。事实上,我根本不建议更改本机端点,除非通过操作和过滤器。
更改 WC REST API 端点行为的一种好的、可重用且面向未来的方法是创建您自己的端点,该端点只需extendsWoocommerce 控制器类,并重写需要自定义的方法。最好不要重写整个方法,而是在自定义方法中包含对父方法的调用。
示例解决方案:(还没有测试过这个特定的解决方案,但最近做了一个非常相似的解决方案)
wp-content/plugins/
woocommerce/
your-plugin/
includes/
class-your-plugin.php
your-plugin.php
your-plugin.php
<?php
defined( 'ABSPATH' ) || exit;
add_action('rest_api_init', function(){
require_once __DIR__ . '/includes/class-your-plugin.php';
$controller = new Your_Custom_Class();
$controller->register_routes();
} );
includes/class-your-plugin.php
<?php
defined( 'ABSPATH' ) || exit;
/**
* Class Your_Custom_Class
*/
class Your_Custom_Class extends WC_REST_Customers_Controller {
/**
* Endpoint namespace.
* Use the wc- prefix to make use of WooCommerce authentication for third-parties.
* @see /wp-content/plugins/woocommerce/includes/api/class-wc-rest-authentication.php:63
*
* @var string
*/
protected $namespace = 'wc-your-route/v1';
public function register_routes() {
register_rest_route(
$this->namespace,
'/' . $this->rest_base . '/your-custom-route',
array(
array(
'methods' => WP_REST_Server::EDITABLE,
'callback' => array( $this, 'your_customized_function' ),
'permission_callback' => array( $this, 'get_items_permissions_check' ),
'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
),
'schema' => array( $this, 'get_item_schema' ),
)
);
}
/**
* Your custom function
*/
protected function your_customized_function( $arg1, $arg2) {
/*******************************
// IMPLEMENT CUSTOM CODE HERE
*******************************/
parent::the_name_of_the_original_function( $arg1, $arg2 );
/*******************************
// IMPLEMENT CUSTOM CODE HERE
*******************************/
}
通过这种方式,您可以根据自己的需要自由扩展 API,利用 WC API 当前和未来的所有功能,并保留本机 API...好吧...本机。
虽然这应该是一个干净且“正确”的解决方案,但如果没有对 PHP 类和继承的深入理解以及良好的 IDE 的使用,我不建议走这条路。