Created
August 12, 2020 15:28
-
-
Save plugin-republic/4869bfb2ecc21b4253036803dfc60c9d to your computer and use it in GitHub Desktop.
Set the product weight based on the value of a field
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Set the product weight based on the value of a field | |
*/ | |
function prefix_save_product_weight( $cart_item_data, $item, $group_id, $field_id, $value ) { | |
// Change the ID here to your calculation field ID | |
if( $field_id == 7489 ) { | |
$cart_item_data['product_extras']['weight'] = $value; | |
} | |
return $cart_item_data; | |
} | |
add_filter( 'pewc_filter_end_add_cart_item_data', 'prefix_save_product_weight', 10, 5 ); | |
// Update the product weight | |
function prefix_set_product_weight( $cart ) { | |
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) { | |
return; | |
} | |
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) { | |
return; | |
} | |
foreach( $cart->get_cart() as $cart_item ) { | |
if ( isset($cart_item['product_extras']['weight']) ) { | |
$cart_item['data']->set_weight($cart_item['product_extras']['weight']); | |
} | |
} | |
} | |
add_filter( 'woocommerce_before_calculate_totals', 'prefix_set_product_weight', 100 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment