So erhalten und ändern Sie den Preis des zweiter Artikel in meinem Warenkorb?
Ich möchte einen Rabatt von -3 % auf das zweite Produkt gewähren (Artikel im Warenkorb bereits nach Preis sortiert, höchster Preis oben).
Ich denke, es muss eingerechnet werden woocommerce_before_calculate_totals
oder wie Rabatt in woocommerce_cart_calculate_fees
?
Danke
Aktualisiert (Kompatibilität mit Woocommerce 3+ hinzugefügt)
Für ein Produkt ist es besser, einen Artikel zu verwenden woocommerce_before_calculate_totals
Aktionshaken:
add_action( 'woocommerce_before_calculate_totals', 'discount_on_2nd_cart_item', 10, 1 );
function discount_on_2nd_cart_item( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Initialising
$count = 0;
$percentage = 3; // 3 %
// Iterating though each cart items
foreach ( $cart->get_cart() as $cart_item ) {
$count++;
if( 2 == $count){ // Second item only
$price = $cart_item['data']->get_price(); // product price
$discounted_price = $price * (1 - ($percentage / 100)); // calculation
// Set the new price
$cart_item['data']->set_price( $discounted_price );
break; // stop the loop
}
}
}
Oder nutzen Sie einen Warenkorbrabatt (negative Warenkorbgebühr):
add_action( 'woocommerce_cart_calculate_fees', 'discount_on_2nd_cart_item', 10, 1 );
function discount_on_2nd_cart_item( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Initialising
$count = 0;
$percentage = 3; // 3 %
// Iterating though each cart items
foreach ( $cart->get_cart() as $cart_item ) {
$count++;
if( 2 == $count){ // Second item only
$price = $cart_item['data']->get_price(); // product price
$discount = $price * $percentage / 100; // calculation
$second_item = true;
break; // stop the loop
}
}
if( isset($discount) && $discount > 0 )
$cart->add_fee( __("2nd item 3% discount", 'woocommerce'), -$discount );
}
Der Code befindet sich in der Datei „function.php“ Ihres aktiven untergeordneten Themas (oder Themes) oder auch in einer beliebigen Plugin-Datei.
Dieser Code wurde getestet und funktioniert.