且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Woocommerce中价格较低的产品的购物车折扣

更新时间:2023-10-25 15:03:16

对于购物车费用,您应该这样使用woocommerce_cart_calculate_fees专用钩子:

For Cart fees, you should use woocommerce_cart_calculate_fees dedicated hook instead this way:

add_action('woocommerce_cart_calculate_fees', 'discount_on_cheapest_cart_item', 20, 1 );
function discount_on_cheapest_cart_item( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) 
        return;

    // Only for 2 items or more
    if ( $cart->get_cart_contents_count() < 2 ) return;

    // Initialising
    $percentage = 10; // 10 %
    $discount = 0;
    $item_prices = array();

    // Loop though each cart items and set prices in an array
    foreach ( $cart->get_cart() as $cart_item ) {
        $product_prices_excl_tax[] = wc_get_price_excluding_tax( $cart_item['data'] );
    }
    sort($product_prices_excl_tax);

    $discount = reset($product_prices_excl_tax) * $percentage / 100;

    $cart->add_fee( "Discount on cheapest (".$percentage."%)", -$discount );
}

代码进入您的活动子主题(或活动主题)的function.php文件中.经过测试,可以正常工作.

Code goes in function.php file of your active child theme (or active theme). Tested and works.