且构网

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

对非“待售"商品应用欢迎折扣WooCommerce中的项目

更新时间:2023-11-30 11:50:04

如果您为尚未购买的新客户提供欢迎折扣,那么您的代码将变得毫无复杂性,因此,我简化了代码并简化了代码.

Your code is complicated for nothing if you are applying a welcome discount for new customers that doesn't have purchased yet, so I have simplified and lighten your code.

然后将购物车小计为非待售"商品,您需要遍历购物车商品才能获得的商品.

Then to get the cart subtotal for non "On sale" items you need to loop through cart items to get it.

重新访问的代码:

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

    $user_id = get_current_user_id();

    if( $user_id > 0 ) {
        $percentage   = 5; // Discount percentage
        $orders_count = (int) wc_get_customer_order_count($user_id);
        $subtotal     = 0; // Initializing

        // Loop through cart items
        foreach( $cart->get_cart() as $cart_item ) {
            // Add non on sale items to subtotal
            if( ! $cart_item['data']->is_on_sale() ) {
                $subtotal += $cart_item['line_subtotal'];
            }
        }

        // Discount percentage amount on non "on sale" items subtotal
        $discount = $subtotal * $percentage / 100;

        // For new customer only that haven't purchase yet
        if( $subtotal > 0 && $orders_count === 0 ) {
            $cart->add_fee( sprintf( __("Discount (%s)", "woocommerce"), $percentage . '%'), -$discount, true );
        }
    }
}

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

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