I'm using Add fee to Woocommerce Shipping Class without the use of zones or flat rate answer code, that allows me add an additional 'Fee' if any product from the 'Dangerous Goods' shipping class has been added to cart.
This is great as it allows me to cover the additional costs associated to packaging/shipping, however it is also adding the 'fee' when users select 'Local Pickup' shipping option.
I would love to exclude 'Local Pickup' from the additional fee if selected.
Therefore i use:
function fees_fees_fees() {
$shippingClasses['dangerous-goods'] = ['description' => 'Dangerous Goods Fee', 'fee' => 130];
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$shipping_class = get_the_terms( $values['product_id'], 'product_shipping_class' );
foreach($shippingClasses as $key => $val) {
if ( isset( $shipping_class[0]->slug ) && in_array( $shipping_class[0]->slug, [$key] ) ) {
WC()->cart->add_fee( __($val['description'], 'woocommerce'), $val['fee'] ); }
}
}
}
add_action( 'woocommerce_cart_calculate_fees', 'fees_fees_fees' );
However, I'm stuck on the next step. Any adivce?
CodePudding user response:
Simply add check to slug.
if ( isset( $shipping_class[0]->slug ) && in_array( $shipping_class[0]->slug, [$key] ) && $shipping_class[0]->slug != 'local_pickup') {
CodePudding user response:
- The use of
WC()->cart
is not necessary, as$cart
is already passed to the callback function WC()->session->get( 'chosen_shipping_methods' )
can be used to get the chosen shipping method, then it is a matter of adding an if condition
So you get:
function action_woocommerce_cart_calculate_fees( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
// Get chosen shipping method
$chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods' );
$chosen_shipping_method = substr( $chosen_shipping_methods[0], 0, strpos( $chosen_shipping_methods[0], ':' ) );
// NOT for local pickup
if ( $chosen_shipping_method != 'local_pickup' ) {
// Settings
$shipping_classes['dangerous-goods'] = [ 'description' => 'Dangerous Goods Fee', 'fee' => 130 ];
// Loop though cart items
foreach ( $cart->get_cart() as $cart_item ) {
$shipping_class = get_the_terms( $cart_item['product_id'], 'product_shipping_class' );
foreach ( $shipping_classes as $key => $val ) {
if ( isset( $shipping_class[0]->slug ) && in_array( $shipping_class[0]->slug, [$key] ) ) {
$cart->add_fee( __( $val['description'], 'woocommerce' ), $val['fee'] );
}
}
}
}
}
add_action( 'woocommerce_cart_calculate_fees', 'action_woocommerce_cart_calculate_fees', 10, 1 );