php WooCommerce结帐费用基于购物车项目计数与类别除外

dpiehjr4  于 2022-11-21  发布在  PHP
关注(0)|答案(1)|浏览(129)

我试图使自定义结帐费用,如果有更多的项目在购物车5或10,但我也必须排除类别“门票”和“优惠券”计数.我发现good code examples,但没有一个负类别选择,我真的不想设置规则手动为我所有的20+类别,如in this post,最好将其应用于除2个类别之外的所有类别。
下面是我的代码,不工作:

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

// Below your category term ids, slugs or names to be excluded
$excluded_terms = array('tickets', 'vouchers'); 

$cart_item_count    = 0; // Initializing

// Loop through cart items 
foreach ( WC()->cart->get_cart() as $item ) {
    // Excluding some product category from the count
    if ( ! has_term( $excluded_terms, 'product_cat', $item['product_id'] ) ) {
        $items_count += $item['quantity'];
    }
}

// CONDITIONAL ITEMS QUANTITY FEE AMOUNT
if( $cart_item_count < 6 )
    $fee = 0;
elseif( $cart_item_count >= 6 && $cart_item_count < 11 )
    $fee = 3;
elseif( $cart_item_count >= 11 )
    $fee = 5;

if( $fee > 0 )
    $cart->add_fee( __( "Handling Fee", "woocommerce" ), $fee, true);
}

有什么问题吗?任何代码更正将不胜感激。谢谢。
编辑:我最终使用了这个答案:WooCommerce快速购物车费用

ss2ws0br

ss2ws0br1#

你可以试试下面的代码,我已经修改了你的代码一点点:

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

// Below your category term ids, slugs or names to be excluded
$excluded_terms = array('tickets', 'vouchers');
$fee = 0;
$cart_item_count = count( WC()->cart->get_cart() ); // Initializing

// Loop through cart items 
foreach ( WC()->cart->get_cart() as $item ) {
    // Excluding some product category from the count
    if ( has_term( $excluded_terms, 'product_cat', $item['product_id'] ) ) {
        $cart_item_count = $cart_item_count - 1;
    }
}

// CONDITIONAL ITEMS QUANTITY FEE AMOUNT
if( $cart_item_count < 2 )
    $fee = 6;
elseif( $cart_item_count >= 6 && $cart_item_count < 11 )
    $fee = 3;
elseif( $cart_item_count >= 11 )
    $fee = 5;

if( $fee > 0 )
    $cart->add_fee( __( "Handling Fee", "woocommerce" ), $fee, true);
}

相关问题