Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save plugin-republic/9127f0380fe3ea3833617256bb9c6804 to your computer and use it in GitHub Desktop.

Select an option

Save plugin-republic/9127f0380fe3ea3833617256bb9c6804 to your computer and use it in GitHub Desktop.
<?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 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment