Reduce Stock Based on Custom Variation Field Rather than Attribute (Working Script)


I currently have a script that works perfectly. The issue is, I want to use the value in a custom field I have created for my variations rather than an attribute. See code:

// reduce stock based on 'pa_weight' attribute
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_weight');

    // 'pa_weight' attribute value is "15 grams" - keep only the numbers
    $quantity_grams = preg_replace('/[^0-9.]+/', '', $term_name);

    // new quantity
    if( is_numeric ( $quantity_grams ) && $quantity_grams != 0 )
        $quantity *= $quantity_grams;

    return $quantity;

I have tried replacing

$term_name = $product->get_attribute('pa_weight');


$term_name = $product->get_post_meta('custom_field', true);

And similar things, but keep getting undefined method errors and the like. It is as though the value isn’t being properly called.

Any idea? TIA.

, , , Bruce Banner 3 years 2020-04-03T20:50:58-05:00 0 Answers 91 views 0

Leave an answer