Update WooCommerce Delivery Cost With Condition | Code For Developers

Update WooCommerce Delivery cost with condition

Change Delivery price base on what item in cart

/**
 * Add extra price to shipping for a product
 */
add_filter( 'woocommerce_shipping_method_add_rate_args', 'snippet_charge_shipping_extra_per_product', 100, 2 );
function snippet_charge_shipping_extra_per_product( $args, $shipping_method ) {
	// Check that cart contains a product named "Bananas"
	$contains = false;
	foreach ( WC()->cart->get_cart() as $key => $item ) {
		if ( isset( $item['data'] ) && method_exists( $item['data'], 'get_title' ) && $item['data']->get_title() === "Bananas" ) {
			$contains = true;
			break;
		}
	}
	
	// Check that we are processing Economy Shipping method
	if ( $contains && $shipping_method && $shipping_method->get_title() === "Economy Shipping" ) {
		// Add extra of $ 3 to the shipping method. Extra price is added to $args['cost']
		// Taxes will be calculated from the new price.
		$args['cost'] += 3;
	}

	return $args;
}

If you did not see the changes turn on debug mood

September 25, 2021

When we work with conditions often need to know different values. To check values at the cart page use the code below

// define the woocommerce_before_cart callback 
function action_woocommerce_before_cart( $wccm_before_checkout ) { 
	foreach ( WC()->cart->get_cart() as $key => $item ) {
		echo '<pre>';
		print_r($item);
		echo '</pre>';
	}
}; 
         
// add the action 
add_action( 'woocommerce_before_cart', 'action_woocommerce_before_cart', 10, 1 );
Previous Code

JS set interval for an event until element show

Sometimes we need to active an event when a specif ...

Next Code

Jquery Replace specific text in all element

TweetShareSharePin0 Shares ...

Leave a Reply

Your email address will not be published. Required fields are marked *

If you find it useful

Buy me a coffee

ACF

Elementor

JavaScript

jQuery

Others

PHP

WooCommerce

WordPress

WP Plugin Dev

WooCommerce Ajax Product Search and Category Filter Without Plugin

WooCommerce Ajax Product Search with Category Filt ...

Replace add to cart button with the product page link & Change add to cart text

`Replace add to cart button with product single li ...

Add an additional custom checkbox in the WooCommerce checkout

Add an additional custom checkbox after the terms ...

Making Specific Products Unpurchasable or purchasable for a specific date in WooCommerce

How to make specific products not purchasable in W ...

Implementing WooCommerce Shop Page Quantity Input and Plus (+) Minus (-) Button with simple Code

Enhance the user experience on your WooCommerce we ...

top