Skip to content

Instantly share code, notes, and snippets.

@plugin-republic
Created August 12, 2020 15:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save plugin-republic/4869bfb2ecc21b4253036803dfc60c9d to your computer and use it in GitHub Desktop.
Save plugin-republic/4869bfb2ecc21b4253036803dfc60c9d to your computer and use it in GitHub Desktop.
Set the product weight based on the value of a field
<?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