Chr*_*des 5 php api woocommerce-rest-api
我正在使用 WooCommerce REST API 来获取所有具有变化的产品,但是我遇到了一个关于触发请求数量的相当大的问题。我需要帮助优化下面的情况。
情况:一家拥有 50 种产品和每种产品 5 种变体的网上商店。
请求总数 = 51
如何在不触发 51 个请求的情况下执行此操作?是否不可能以某种方式急切加载所有产品及其变体?
是的,您可以通过自定义 WooCommerce 产品 REST API 响应来实现。
在这里,我附上了一些可以帮助您的代码。
add_filter('woocommerce_rest_prepare_product_object', 'custom_change_product_response', 20, 3);
add_filter('woocommerce_rest_prepare_product_variation_object', 'custom_change_product_response', 20, 3);
function custom_change_product_response($response, $object, $request) {
$variations = $response->data['variations'];
$variations_res = array();
$variations_array = array();
if (!empty($variations) && is_array($variations)) {
foreach ($variations as $variation) {
$variation_id = $variation;
$variation = new WC_Product_Variation($variation_id);
$variations_res['id'] = $variation_id;
$variations_res['on_sale'] = $variation->is_on_sale();
$variations_res['regular_price'] = (float)$variation->get_regular_price();
$variations_res['sale_price'] = (float)$variation->get_sale_price();
$variations_res['sku'] = $variation->get_sku();
$variations_res['quantity'] = $variation->get_stock_quantity();
if ($variations_res['quantity'] == null) {
$variations_res['quantity'] = '';
}
$variations_res['stock'] = $variation->get_stock_quantity();
$attributes = array();
// variation attributes
foreach ( $variation->get_variation_attributes() as $attribute_name => $attribute ) {
// taxonomy-based attributes are prefixed with `pa_`, otherwise simply `attribute_`
$attributes[] = array(
'name' => wc_attribute_label( str_replace( 'attribute_', '', $attribute_name ), $variation ),
'slug' => str_replace( 'attribute_', '', wc_attribute_taxonomy_slug( $attribute_name ) ),
'option' => $attribute,
);
}
$variations_res['attributes'] = $attributes;
$variations_array[] = $variations_res;
}
}
$response->data['product_variations'] = $variations_array;
return $response;
}
Run Code Online (Sandbox Code Playgroud)
我就是通过这种方式做到的。我在单个参数中得到了所有变化product_variations。