Skip to content

Instantly share code, notes, and snippets.

@bolderelements
Last active February 14, 2018 02:52
Show Gist options
  • Save bolderelements/0e4fd316ae3402b0ec8dce4e1c3d106e to your computer and use it in GitHub Desktop.
Save bolderelements/0e4fd316ae3402b0ec8dce4e1c3d106e to your computer and use it in GitHub Desktop.
Add shipping surcharge for one class of items in cart
add_filter( 'woocommerce_package_rates', 'add_shipping_option_base_fee', 10, 2 );
function add_shipping_option_base_fee( $rates, $package ) {
foreach( $rates as $key => $rate ) {
// reset defaults
$class_c_items = 0;
// Do not apply base fee if not the right option
if( $rate->id !== 'betrs_shipping:1-1' ) continue;
// find items belonging to a specific shipping class
foreach( $package['contents'] as $key => $values ) {
$item_sclass = $values[ 'data' ]->get_shipping_class();
if( $item_sclass == 'class-c-slug' ) {
$class_c_items += $values['quantity'];
}
}
// Add $1 surcharge for every 5 Class C items
if( $class_c_items > 0 ) {
$rates[ $key ]->cost += ceil($class_c_items / 5) * 1;
}
}
return $rates;
}
@R33D3M33R
Copy link

It works. To use num items in cart line 15 should be: $class_c_items += $values['quantity'];

@bolderelements
Copy link
Author

Good catch, thank you! I have updated the code accordingly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment