Wordpress WooCommerce Rest-API 覆盖项目架构

Wordpress WooCommerce Rest-API override item schema

我正在尝试通过插件 [Quantities and Units for WooCommerce][1] 将 WooCommerce 与小数库存量一起使用,效果非常好。我唯一的问题是,WooCommerce API 拒绝带小数点的数量,因为 Rest Products Controller (class-wc-rest-products-controller.php) 中的项目模式将其定义为整数(验证)。

如何在不修改 WooCommerce 源代码的情况下在插件中覆盖此架构?

解决方案是,创建所需 WooCommerce 控制器的子类,重新附加其余路由并覆盖 get_item_schema 函数。

例如(将数量类型替换为数字而不是整数):

class WC_REST_Products_Quantity_Controller extends WC_REST_Products_Controller {
    public function __construct() {
        parent::__construct();

        add_action( 'rest_api_init', array( $this, 'register_rest_routes' ), 8 );
    }

    /**
     * Register the routes for products.
     */
    public function register_rest_routes() {
        register_rest_route(
            $this->namespace, '/' . $this->rest_base . '/(?P<id>[\d]+)', array(
                'args'   => array(
                    'id' => array(
                        'description' => __( 'Unique identifier for the resource.', 'woocommerce' ),
                        'type'        => 'integer',
                    ),
                ),
                array(
                    'methods'             => WP_REST_Server::EDITABLE,
                    'callback'            => array( $this, 'update_item' ),
                    'permission_callback' => array( $this, 'update_item_permissions_check' ),
                    'args'                => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
                ),
                'schema' => array( $this, 'get_public_item_schema' ),
            )
        );
    }

    public function update_item($request) {
        return parent::update_item($request);
    }
    public function get_item_schema()
    {
        $res = parent::get_item_schema();

        $res["properties"]["stock_quantity"]["type"] = "number";

        return $res;
    }
}

new WC_REST_Products_Quantity_Controller();