It might be that some of your product add-ons will affect the product weight. One way to do this is to use child products, which will have their own weights.
But if you don’t want to use child products, you can use the following code to add a new weight parameter to radio or select fields.
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 | |
/** | |
* Add a custom weight parameter to add-on field settings | |
*/ | |
function prefix_add_option_param( $option_count, $group_id, $item_key, $item, $key ) { | |
$name = '_product_extra_groups_' . esc_attr( $group_id ) . '_' . esc_attr( $item_key ) . '[field_options][' . esc_attr( $option_count ) . ']'; | |
$weight = isset( $item['field_options'][esc_attr( $key )]['weight'] ) ? $item['field_options'][esc_attr( $key )]['weight'] : ''; | |
?> | |
<td class="pewc-option-extra"> | |
<input type="number" class="pewc-field-option-weight" name="<?php echo $name; ?>[weight]" value="<?php echo esc_attr( $weight ); ?>" step="0.01"> | |
</td> | |
<?php } | |
add_action( 'pewc_after_option_params', 'prefix_add_option_param', 10, 5 ); | |
/** | |
* Add the new weight param to the cart item data | |
*/ | |
function prefix_end_add_cart_item_data( $cart_item_data, $item, $group_id, $field_id, $value ) { | |
if( ! empty( $item['field_options'] ) ) { | |
// Check if $value was originally an array | |
if( strpos( $value, ' | ' ) !== false ) { | |
$value_arr = explode( ' | ', $value ); | |
} else { | |
$value_arr = array( $value ); | |
} | |
foreach( $value_arr as $value ) { | |
foreach( $item['field_options'] as $option ) { | |
$option_len = strlen( $option['value'] ); | |
if( substr( $value, 0, $option_len ) == $option['value'] ) { | |
$weight = isset( $cart_item_data['product_extras']['weight'] ) ? $cart_item_data['product_extras']['weight'] : 0; | |
$weight += floatval( $option['weight'] ); | |
$cart_item_data['product_extras']['weight'] = $weight; | |
} | |
} | |
} | |
} | |
return $cart_item_data; | |
} | |
add_filter( 'pewc_filter_end_add_cart_item_data', 'prefix_end_add_cart_item_data', 10, 5 ); | |
// Update the weight | |
function prefix_get_item_data( $item_data, $cart_item ) { | |
if( ! empty( $cart_item['product_extras']['weight'] ) ) { | |
$item_weight = $cart_item['data']->get_weight(); | |
$item_weight = $cart_item['product_extras']['weight']; | |
$item_data[] = array( | |
'key' => __('Weight', 'woocommerce'), | |
'value' => $item_weight, | |
'display' => $item_weight . ' ' . get_option('woocommerce_weight_unit') | |
); | |
} | |
return $item_data; | |
} | |
add_filter( 'woocommerce_get_item_data', 'prefix_get_item_data', 10, 2 ); |