php – 按属性值减少WooCommerce项目库存

我有一个Woocommerce“可变产品”的设置,唯一的变化是’尺寸’属性:15克,100克,250克.我想要做的是使用该变化量传递给Woo wc-stock-functions,这样当购买产品变化’15克’时,整体库存下降15而不是1.

在Woo内部,有文件wc-stock-functions(http://hookr.io/plugins/woocommerce/3.0.6/files/includes-wc-stock-functions/) – 这甚至提供了一个过滤器,woocommerce_order_item_quantity.我想用它来将库存数乘以克数,并以克为单位减少库存.

我正在尝试这个:

// 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 ); 

但我现在收到内部服务器错误作为回应.

有没有人知道我上面的代码做错了什么?谢谢你的帮助.

解决方法:

第一个错误在$item-> get_attribute(‘pa_size’);因为$item是WC_Order_Item_Product对象的实例,并且WC_Order_Item_Product类不存在get_attribute()方法.

相反,您需要使用WC_Order_Item_Product Class中的get_product()方法获取WC_Product对象的实例…

所以你的代码应该是:

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;
}

代码位于活动子主题(或活动主题)的function.php文件中.经过测试和工作.

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)

相关文章

我们有时候在定制WORDPRESS主题的时候,由于菜单样式的要求我...
很多朋友在做wordpree主题制作的时候会经常遇到一个问题,那...
wordpress后台的模块很多,但并不是每个都经常用到。介绍几段...
从WordPress4.2版本开始,如果我们在MYSQL5.1版本数据中导出...
很多网友会遇到这样一个问题,就是WordPress网站上传图片、附...
对于经常要在文章中出现代码的IT相关博客,安装一个代码高亮...