【问题标题】:WooCommerce Product Category and City Based Shipping FeeWooCommerce 产品类别和基于城市的运费
【发布时间】:2020-05-03 20:49:34
【问题描述】:

我在这里有一个场景。

在我设置的 WooCommerce 商店中,产品类​​别 'Bronx' 是父类别,'Baby Items Bronx' 是它的子类别。此处父类别名称布朗克斯是销售'Baby Items Bronx' 下产品的城市。

另一个产品类别'Newark' 是父类别,'Baby Items Newark' 是它的子类别。此处父类别名称 Newark 是销售'Baby Items Newark' 下产品的城市。

布朗克斯的客户正在尝试购买'Baby Items Newark' 类别的产品。

我正在尝试在 WooCommerce 中设置自定义运费,它可以根据客户的位置计算运费并添加自定义运费。如果客户使用此代码在帐单地址中选择城市为布朗克斯,我能够实现添加费用。

function from_to_city_add_checkout_fee() {
    if (($_POST['city']=='Bronx')){
        WC()->cart->add_fee( 'Delivery Fee', 15 );
    }

现在我需要一个函数来计算费用,如果客户来自 布朗克斯 并且尝试购买父类别下列出的产品是 'Newark'

我尝试了以下代码,但它不起作用。

function from_to_city_add_checkout_fee() {
    if (($_POST['city']=='Bronx') && (has_term( array( 'baby-items-newark' ), 'product_cat' ))){
        WC()->cart->add_fee( 'Fee', 150 );
    }   
}

我尝试使用从https://businessbloomer.com/woocommerce-check-product-category-cart/ 获得的代码 sn-p 执行类似的操作,以帮助检查购物车中的产品类别,但它仍然不起作用。

add_action('woocommerce_before_cart', 'bbloomer_check_category_in_cart');

function bbloomer_check_category_in_cart() {

// Set $cat_in_cart to false
$cat_in_cart = false;

// Loop through all products in the Cart        
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {

    // If Cart has category "download", set $cat_in_cart to true
    if ( has_term( 'baby-items-newark', 'product_cat', $cart_item['product_id'] ) ) {
        $cat_in_cart = true;
        break;
    }
}

// Do something if category "download" is in the Cart      
if ( $cat_in_cart == true) {

// For example, print a notice
// Or maybe run your own function...
function from_to_city_add_checkout_fee() {
    if (($_POST['city']=='Bronx')){
        WC()->cart->add_fee( 'Delivery Fee', 150 );
    }


}

}

感谢任何帮助。

【问题讨论】:

    标签: php wordpress woocommerce checkout shipping


    【解决方案1】:

    试试下面的代码 sn-p。 并用您的逻辑替换 if 条件。

    add_action('woocommerce_cart_calculate_fees', 'woocommerce_custom_surcharge', 10, 1);
    function woocommerce_custom_surcharge($cart)
    {
        global $woocommerce;
    
        if (is_admin() && !defined('DOING_AJAX'))
            return;
    
        foreach ($cart->get_cart() as $cart_item) {
            $product = $cart_item['data'];
            if (
                $woocommerce->customer->get_shipping_city() == "Bronx" &&
                has_term('baby-items-newark', 'product_cat', $product->id)
            ) :
                WC()->cart->add_fee('Fee', 150);
            endif;
        }
    }
    

    你可以从

    获取父类
    $parentcats = get_ancestors($product_cat_id, 'product_cat');
    

    我宁愿创建一个运输类别并在条件为真时添加它,以便应用不同的运输费用。
    当您在产品中使用城市的自定义字段而不是类别时,也很容易。

    【讨论】:

    • 顺便说一句,这需要更换,$product->id$product->get_id() 以防止 id was called incorrectly error_log 警告。
    猜你喜欢
    • 2018-01-04
    • 1970-01-01
    • 2018-10-12
    • 2021-05-19
    • 2019-12-19
    • 2018-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多