在Woocommerce中为特定产品类别添加费用

在Woocommerce中为特定产品类别添加费用

本文介绍了在Woocommerce中为特定产品类别添加费用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在这里找到了此代码,对我来说它的工作效率为80/90%(见下文).

I already found this code here and it works for like 80/90% for me (see below).

当购物车中有类别ID 349的商品时,此代码为我的购物车增加60欧元.当我将购物车中的商品从该类别添加到购物车时,它可以正常工作.但是,当我的购物车中已经有其他类别的产品,然后添加类别349的产品时,它不会增加60欧元的额外费用.这怎么可能?

This code adds 60 euro to my cart when there is a product from category ID 349 in the cart. When I add a product from that category to my cart when the cart is empty it works fine. But when there is already a product in my cart from a different category and then I add the product with category 349 it doesn't add the 60 euro extra fee. How is this possible?

 function woo_add_cart_fee() {

$category_ID = '349';
global $woocommerce;

foreach ($woocommerce->cart->cart_contents as $key => $values ) {
    // Get the terms, i.e. category list using the ID of the product
$terms = get_the_terms( $values['product_id'], 'product_cat' );
    // Because a product can have multiple categories, we need to iterate through the list of the products category for a match
    foreach ($terms as $term) {
        // 349 is the ID of the category for which we want to remove the payment gateway
        if($term->term_id == $category_ID){
         $excost = 60;
         }
         }
        $woocommerce->cart->add_fee('Extra bezorgkosten kunstgras', $excost, $taxable = false, $tax_class = '');
}
}
add_action( 'woocommerce_cart_calculate_fees', 'woo_add_cart_fee' );

推荐答案

您使用的代码有些过时了,您应该使用has_term() Wordpress条件函数以这种方式定位产品类别:

The code you are using is a bit outdated and you should use has_term() Wordpress conditional function to target a product category this way:

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

    // Set HERE your categories (can be term IDs, slugs or names) in a coma separated array
    $categories = array('349');
    $fee_amount = 0;

    // Loop through cart items
    foreach( $cart->get_cart() as $cart_item ){
        if( has_term( $categories, 'product_cat', $cart_item['product_id']) )
            $fee_amount = 60;
    }

    // Adding the fee
    if ( $fee_amount > 0 ){
        // Last argument is related to enable tax (true or false)
        WC()->cart->add_fee( __( "Extra bezorgkosten kunstgras", "woocommerce" ), $fee_amount, false );
    }
}

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

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

这篇关于在Woocommerce中为特定产品类别添加费用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 01:12