You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

按属性值扣减WooCommerce商品库存的技术实现问询

Adjust WooCommerce Stock Deduction Based on Variant Size Attribute

Hey there! I’ve got you covered on this. To make your WooCommerce store deduct stock based on the "size" variant value (like subtracting 15 instead of 1 when someone buys the 15g option), we’ll use the woocommerce_order_item_quantity filter you mentioned from the wc-stock-functions file. Here’s a step-by-step solution:

Step 1: Add the Custom Filter Code

You’ll want to add this code to your theme’s functions.php file or a custom plugin (never edit core WooCommerce files directly—they’ll get overwritten on updates):

add_filter( 'woocommerce_order_item_quantity', 'adjust_stock_deduction_by_variant_weight', 10, 3 );
function adjust_stock_deduction_by_variant_weight( $quantity, $order_item, $order ) {
    // Only target variable product variations
    $product = $order_item->get_product();
    if ( ! $product || ! $product->is_type( 'variation' ) ) {
        return $quantity;
    }

    // Get the "size" attribute value (e.g., "15克", "100克")
    $size_attribute = $product->get_attribute( 'size' );
    
    // Extract the numeric value from the attribute string
    preg_match( '/\d+/', $size_attribute, $weight_matches );
    if ( empty( $weight_matches ) ) {
        return $quantity; // Fallback if no number is found
    }
    $weight_number = (int) $weight_matches[0];

    // Calculate adjusted stock quantity: purchase quantity × weight value
    $adjusted_quantity = $quantity * $weight_number;

    return $adjusted_quantity;
}

Step 2: Customize if Needed

  • Double-check your attribute slug: If your size attribute has a different slug (like pa_weight instead of size), update $product->get_attribute( 'size' ) to match the correct slug. You can find this in WooCommerce > Products > Attributes.
  • Test thoroughly: Place a test order for each variant to confirm stock is deducted correctly. For example, buying 1x 15g variant should reduce your total stock by 15, not 1.

How This Works

  • The filter hooks into the stock calculation process right before WooCommerce deducts inventory.
  • It checks if the order item is a product variation, then pulls the size attribute value.
  • We use a regular expression to grab the numeric part of the attribute (ignoring the "克" text), then multiply that number by the quantity the customer bought.
  • The adjusted number is returned, telling WooCommerce to deduct that amount from stock instead of the default quantity.

内容的提问来源于stack exchange,提问作者Steve Goerger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:12:24