1. Home
  2. Knowledge Base
  3. WooCommerce Product Add-Ons Ultimate
  4. Advanced Topics for Add-Ons Ultimate
  5. Cart and Order
  6. Update shipping class if product contains specific add-on field
  1. Home
  2. Knowledge Base
  3. WooCommerce Product Add-Ons Ultimate
  4. Update shipping class if product contains specific add-on field
  1. Home
  2. Knowledge Base
  3. Advanced Topics for Add-Ons Ultimate
  4. Update shipping class if product contains specific add-on field

Update shipping class if product contains specific add-on field

You can use this snippet to update the shipping class if a line item in the cart includes a specific add-on field. You’ll need to update the field ID and shipping class slug.

<?php
// Update shipping class if a specific field has any value
// Uncomment line below if you want to check the field for a specific value
add_action( 'woocommerce_before_calculate_totals', function( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
return;
}
$target_field_id = 1642; // the field ID
$shipping_class = 'easy'; // the shipping class slug
$term = get_term_by( 'slug', $shipping_class, 'product_shipping_class' );
if ( ! $term ) {
return;
}
foreach ( $cart->get_cart() as $cart_item ) {
if ( empty( $cart_item['product_extras']['groups'] ) ) {
continue;
}
foreach ( $cart_item['product_extras']['groups'] as $group ) {
// if ( isset( $group[ $target_field_id ]['value'] ) && $group[ $target_field_id ]['value'] === 'Specific Value' ) {
if ( ! empty( $group[ $target_field_id ]['value'] ) ) {
$cart_item['data']->set_shipping_class_id( $term->term_id ); // Set the shipping class ID
$cart_item['data']->save();
break;
}
}
}
}, 20 );

Was this article helpful?

Related Articles