Estoy tratando de agregar un descuento de carrito personalizado basado en un número mínimo de artículos y categorías en el carrito.
He tomado el código de esta respuesta:
Descuento de carrito basado en el número de artículos del carrito y solo para artículos que no están en oferta
He hecho algunos cambios y este es mi código:
add_action('woocommerce_cart_calculate_fees' , 'my_custom_discount', 10, 1); function my_custom_discount( $cart_object ){ if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return; // Only when there is 4 or more items in cart if( $cart_object->get_cart_contents_count() >= 4): // Defining variables $categories = array('mycategory1','mycategory2'); $has_category = false; // Iterating through each item in cart foreach( $cart_object->get_cart() as $cart_item ){ // Getting an instance of the product object $_product = new WC_Product( $cart_item['product_id'] ); // If a cart item has the category if(has_category($category, $_product)){ $has_category = true; break; } } ## Discount calculation ## $discount = $cart_object->subtotal * -0.03; ## Applied discount (no products on sale) ## if($has_category ) $cart_object->add_fee( '3% discount', $discount); endif; }No puedo hacer que funcione.
¿Qué estoy haciendo mal y cómo hacer que funcione?
Gracias
Como las categorías de productos son una taxonomía personalizada 'product_cat' , deberá usar la función condicional has_term() (en lugar de has_category() ) de esta manera:
add_action('woocommerce_cart_calculate_fees' , 'my_custom_discount', 10, 1); function my_custom_discount( $cart_obj ){ if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return; // Only when there is 4 or more items in cart if ( $cart_obj->get_cart_contents_count() > 3): // Set HERE your array of categories (slugs, IDs or names) <== <== <== <== <== $categories = array('mycategory1','mycategory2'); // Initialising variable $has_category = false; // Iterating through each item in cart foreach( $cart_obj->get_cart() as $cart_item ){ // The product ID $product_id = $cart_item['product_id']; // When a cart item is from one defined product categories we set $has_category to true. if ( has_term( $categories, 'product_cat', $product_id ) ) { $has_category = true; break; } } ## Discount calculation ## $discount = $cart_obj->subtotal * -0.03; ## Applied discount (for products (items) of defined product categories) ## if( $has_category ) $cart_obj->add_fee( '3% discount', $discount); endif; }Este código va en el archivo function.php de su tema secundario activo (o tema) o también en cualquier archivo de complemento.
Este código está probado y funciona para WooCommerce versión 2.6+ y 3.0+