Skip to content

Instantly share code, notes, and snippets.

@plugin-republic
Last active March 24, 2022 10:40
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/53dad937927b6ecabc4f065ce525a6eb to your computer and use it in GitHub Desktop.
Save plugin-republic/53dad937927b6ecabc4f065ce525a6eb to your computer and use it in GitHub Desktop.
<?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 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment