modifica-prezzi-articoli-aggiunti-carrello-woocommerce

Modifica i prezzi degli articoli aggiunti al carrello in WooCommerce

Quando un cliente aggiunge al carrello una certa quantità (3 per esempio) di prodotti di una categoria specifica (ID 25), questi prodotti riceveranno uno sconto del 50%. Ma questo non dovrebbe influire sul prodotto Lambo (con ID 12345).

add_action( 'woocommerce_before_calculate_totals', 'misha_recalculate_price' );
 
function misha_recalculate_price( $cart_object ) {

	if ( is_admin() && ! defined( 'DOING_AJAX' ) )
		return;

	// you can always print_r() your object and look what's inside
	//print_r( $cart_object ); exit;
 
	// it is our quantity of products in specific product category
	$quantity = 0;
 
	// $hash = cart item unique hash
	// $value = cart item data
	foreach ( $cart_object->get_cart() as $hash => $value ) {
 
 
		// check if the product is in a specific category and check if its ID isn't 12345
		if( in_array( 25, $value['data']->get_category_ids() ) && $value['product_id'] != 12345 ) {
	 	
			// if yes, count its quantity
			$quantity += $value['quantity'];
    		
		}


	}
 
	// change prices
	if( $quantity > 3 ) {
		foreach ( $cart_object->get_cart() as $hash => $value ) {
 
 
			// I want to make discounts only for products in category with ID 25
			// and I never want to make discount for the product with ID 12345
			if( in_array( 25, $value['data']->get_category_ids() ) && $value['product_id'] != 12345 ) {
    		
				$newprice = $value['data']->get_regular_price() / 2;
    			
				// in case the product is already on sale and it is much cheeper with its own discount
				if( $value['data']->get_sale_price() > $newprice )
					$value['data']->set_price( $newprice );
					
			}
			
		}
	}
 
}

Se leggi il mio blog e ancora non sai dove inserire questo tipo di codice, è triste. Prova il tuo tema attuale functions.php allora.

Se il tuo carrello in WooCommerce è codificato su misura e il nostro hook non si applica ad esso, usa WC()->cart->calculate_totals().

PS Mentre lavori con woocommerce_before_calculate_totalsaction hook, fai attenzione ai plug-in che influiscono anche sui prezzi del carrello, come YITH Dynamic Pricing and Discounts.

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *