Skip to content

Instantly share code, notes, and snippets.

@WhiteHatJoker
Created October 18, 2021 22:58
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 WhiteHatJoker/0c6b2148e31b11c3c990f8c6a15c2d75 to your computer and use it in GitHub Desktop.
Save WhiteHatJoker/0c6b2148e31b11c3c990f8c6a15c2d75 to your computer and use it in GitHub Desktop.
If you have set up shipping classes and assigned products to your shipping categories, then you can see here how to add fees for products from specific shipping classes.

Add fees for specific shipping class categories

If you have set up shipping classes and assigned products to your shipping categories, then you can see here how to add fees for products from specific shipping classes.

Installation

  1. Copy over the code from functions.php to your functions.php copy of WordPress site.
  2. You can remove lines 40-45.
  3. For each shipping class you would like to add fee for, copy and paste lines 46-48.
  4. Now simply update 'your-shipping-class-slug-here' with your shipping class slug, 'Any text you would like to see as fee heading :' with your text and $fixed with your preferred price.
//Function to check if certain shipping class of the product in the cart
function cart_has_product_with_shipping_class( $slug ) {
global $woocommerce;
$product_in_cart = false;
// start of the loop that fetches the cart items
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
$terms = get_the_terms( $_product->id, 'product_shipping_class' );
if ( $terms ) {
foreach ( $terms as $term ) {
$_shippingclass = $term->slug;
if ( $slug === $_shippingclass ) {
// Our Shipping Class is in cart!
$product_in_cart = true;
}
}
}
}
return $product_in_cart;
}
//Handling Fees
add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
function woocommerce_custom_surcharge() {
global $woocommerce;
$fixed = 30;
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if (cart_has_product_with_shipping_class( 'tsar-nicoulai' )) {
$woocommerce->cart->add_fee( 'Tsar Nicoulai Shipping Fee :', $fixed, true, '' );
}
if (cart_has_product_with_shipping_class( 'tonewood' )) {
$woocommerce->cart->add_fee( 'Tonewood Shipping Fee :', $fixed, true, '' );
}
if (cart_has_product_with_shipping_class( 'your-shipping-class-slug-here' )) {
$woocommerce->cart->add_fee( 'Any text you would like to see as fee heading :', $fixed, true, '' );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment