问题
I have a setup with Woocommerce "Variable Products" where the only variation is 'size' attribute: 15 grams, 100 grams, 250 grams. What I want to do is use that variation amount to pass to the Woo wc-stock-functions, so that when a product variation '15 grams' is purchased, the overall stock goes down by 15, not 1.
Inside Woo, there is file wc-stock-functions (http://hookr.io/plugins/woocommerce/3.0.6/files/includes-wc-stock-functions/) - and this even gives a filter, woocommerce_order_item_quantity. I want to use this to multiply the inventory number by the # of grams, and to reduce inventory this way by grams.
I'm trying this:
// define the woocommerce_order_item_quantity callback
function filter_woocommerce_order_item_quantity( $item_get_quantity, $order,
$item ) {
$original_quantity = $item_get_quantity;
$item_quantity_grams = $item->get_attribute('pa_size');
// attribute value is "15 grams" - so remove all but the numerals
$item_quantity_grams = preg_replace('/[^0-9.]+/', '', $item_quantity_grams);
// multiply for new quantity
$item_get_quantity = ($item_quantity_grams * $original_quantity);
return $item_get_quantity;
};
// add the filter
add_filter( 'woocommerce_order_item_quantity',
'filter_woocommerce_order_item_quantity', 10, 3 );
but am getting internal server error as a response right now.
Does anyone have an idea of what I'm doing wrong with the above code? Thanks for any help.
回答1:
First error is in $item->get_attribute('pa_size');
as $item
is an instance of WC_Order_Item_Product
object and get_attribute()
method doesn't exist for WC_Order_Item_Product
Class.
Instead you need to get the an instance of the WC_Product
object using get_product()
method from WC_Order_Item_Product
Class…
So your code should be:
add_filter( 'woocommerce_order_item_quantity', 'filter_order_item_quantity', 10, 3 );
function filter_order_item_quantity( $quantity, $order, $item )
{
$product = $item->get_product();
$term_name = $product->get_attribute('pa_size');
// The 'pa_size' attribute value is "15 grams" And we keep only the numbers
$quantity_grams = preg_replace('/[^0-9.]+/', '', $term_name);
// Calculated new quantity
if( is_numeric ( $quantity_grams ) && $quantity_grams != 0 )
$quantity *= $quantity_grams;
return $quantity;
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
Note: This hooked function is going to reduce the stock quantity based on that new returned increased quantity value (in this case the real quantity multiplied by 15)
来源:https://stackoverflow.com/questions/49680378/reduce-woocommerce-item-inventory-by-attribute-value