1. Home
  2. Knowledge Base
  3. WooCommerce Product Add-Ons Ultimate
  4. Set the product weight based on the value of a field
  1. Home
  2. Knowledge Base
  3. Advanced
  4. Set the product weight based on the value of a field

Set the product weight based on the value of a field

If you are setting the product weight through an add-on field, e.g. via a calculation, you can use this snippet.

Note that you will need to change the value of the field ID to match the field ID you want to use:

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

Here’s how to add the snippet.

Was this article helpful?

Need More Support?

If you can't find the answer that you're looking for, then please use the link below to raise a support ticket.
Contact Support

Related Articles