我正在尝试使用WooCommerce与小数量的插件[WooCommerce的数量和单位] [1]并且效果非常好。我唯一的问题是,WooCommerce API拒绝带小数点的数量,因为Rest Products Controller(class-wc-rest-products-controller.php)中的项目架构将其定义为整数(验证)。
如何在不修改WooCommerce源的情况下在插件中覆盖此架构?
解决方案是,要创建所需WooCommerce Controller的子类,请重新附加其余路由并覆盖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();