WooCommerce动态最低订单金额费用

时间:2017-08-18 16:47:11

标签: php wordpress woocommerce checkout cart

我需要在购物车中设置最低订购费用,因此如果购物车中的商品总价不超过10英镑,则需要支付额外费用才能将价格提高到10英镑。

以下是我目前在购物车阶段运作良好的代码,但是当您到达结账时,定价部分因某些原因没有停止加载而您无法结账,任何人都可以帮忙吗?

来自functions.php的代码:

function woocommerce_custom_surcharge() {
  global $woocommerce;
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;
    $minimumprice = 10;
    $currentprice = $woocommerce->cart->cart_contents_total;
    $additionalfee = $minimumprice - $currentprice;
    if ( $additionalfee >= 0 ) {
        wc_print_notice(
            sprintf( 'We have a minimum %s per order. As your current order is only %s, an additional fee will be applied at checkout.' ,
                wc_price( $minimumprice ),
                wc_price( $currentprice )
            ), 'error'
        );
        $woocommerce->cart->add_fee( 'Minimum Order Adjustment', $additionalfee, true, '' );
    }
}
add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );

1 个答案:

答案 0 :(得分:1)

2019年5月增强且更新

当您在 wc_print_notice() 挂钩中使用 woocommerce_cart_calculate_fees 时,您遇到的无限加载旋转问题。这似乎是一个错误。

如果您使用 wc_add_notice() ,问题就会消失,但通知会显示2次。

此外,我已重新访问您的代码。唯一的解决方案是将其拆分为2个独立的函数(以及消息的第三个函数)

// Add a custom fee (displaying a notice in cart page)
add_action( 'woocommerce_cart_calculate_fees', 'add_custom_surcharge', 10, 1 );
function add_custom_surcharge( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_cart_calculate_fees' ) >= 2 )
        return;

    $min_price     = 100; // The minimal cart amount

    $current_price = $cart->cart_contents_total;
    $custom_fee    = $min_price - $current_price;

    if ( $custom_fee > 0 ) {
        $cart->add_fee( __('Minimum Order Adjustment'), $custom_fee, true );

        // NOTICE ONLY IN CART PAGE
        if( is_cart() ){
            wc_print_notice( get_custom_fee_message( $min_price, $current_price ), 'error' );
        }
    }
}

// Displaying the notice on checkout page
add_action( 'woocommerce_before_checkout_form', 'custom_surcharge_message', 10 );
function custom_surcharge_message(  ) {
    $min_price     = 100; // The minimal cart amount

    $cart          = WC()->cart;
    $current_price = $cart->cart_contents_total;
    $custom_fee    = $min_price - $current_price;

    // NOTICE ONLY IN CHECKOUT PAGE
    if ( $custom_fee > 0 ) {
        wc_print_notice( get_custom_fee_message( $min_price, $current_price ), 'error' );
    }
}

// The fee notice message
function get_custom_fee_message( $min_price, $current_price ) {
    return sprintf(
        __('We have a minimum %s per order. As your current order is only %s, an additional fee will be applied.', 'woocommerce'),
        wc_price( $min_price ),
        wc_price( $current_price )
    );
}

代码进入活动子主题(或活动主题)的functions.php文件。经过测试和工作。