程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了如果 WooCommerce 购物车包含至少 X 个产品,则自动添加百分比折扣大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决如果 WooCommerce 购物车包含至少 X 个产品,则自动添加百分比折扣?

开发过程中遇到如果 WooCommerce 购物车包含至少 X 个产品,则自动添加百分比折扣的问题如何解决?下面主要结合日常开发的经验,给出你关于如果 WooCommerce 购物车包含至少 X 个产品,则自动添加百分比折扣的解决方法建议,希望对你解决如果 WooCommerce 购物车包含至少 X 个产品,则自动添加百分比折扣有所启发或帮助;

我正在尝试创建一个自动折扣,当购物车包含至少三件或更多产品时,该折扣就会生效。

如果是这样,无论客户是否登录,都应给予 10% 的折扣。

这是我试图开始工作的代码(没有成功)。

add_action( 'woocommerce_cart_calculate_fees','wc_discount_when_more_than_three',10,1 );
function wc_discount_when_more_than_three( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )

        return;

    $percentage = 10; // 10% discount when cart has a minimum of three products
    $discount = 0;

    // check all cart items
    foreach ( $cart->get_cart() as $cart_item ) {

    // when quantity is more than 3
    if( $cart_item['quantity'] > 3 ) {

    // give 10% discount on the sub@R_871_10586@l
    $discount = $percentage / 100;
    }
}
    
    if( $discount > 0 )
    $cart->add_fee( __( '10% OFF','woocommerce' ),-$discount );
}

解决方法

这取决于您是要计算购物车中的产品数量还是产品数量(内容)。

在我的回答中,我已经说明了两者,取消注释/删除/根据您的需要进行调整。

function action_woocommerce_cart_calculate_fees( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;
    
     // Percentage
    $percentage = 10;

    /* Count contents in cart
     *
     * Product A: quantity in cart: 4 
     * Product B: quantity in cart: 1 
     * Product C: quantity in cart: 2
     *
     * count = 7
     *
     */
    //$count = $cart->cart_contents_count;
    
    /* Count products in cart
     *
     * Product A
     * Product B 
     * Product C
     *
     * count = 3
     */
    $count = count( $cart->get_cart() );
    
    // Greater than
    if ( $count > 3 ) {
        // Get sub@R_871_10586@l
        $sub@R_871_10586@l = $cart->sub@R_871_10586@l;
        
        // Calculate
        $discount = ( $sub@R_871_10586@l / 100 ) * $percentage;
        
        // Give % discount on the sub@R_871_10586@l
        $cart->add_fee( sprintf( __( '%s OFF','woocommerce'),$percentage . '%' ),-$discount );
    }
}
add_action( 'woocommerce_cart_calculate_fees','action_woocommerce_cart_calculate_fees',10,1 );

大佬总结

以上是大佬教程为你收集整理的如果 WooCommerce 购物车包含至少 X 个产品,则自动添加百分比折扣全部内容,希望文章能够帮你解决如果 WooCommerce 购物车包含至少 X 个产品,则自动添加百分比折扣所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。