【问题标题】:Enable shipping address for specific virtual products from a product category in Woocommerce checkout在 Woocommerce 结帐中为产品类别中的特定虚拟产品启用送货地址
【发布时间】:2019-05-19 09:30:51
【问题描述】:

我有一个类别门,用于显示虚拟产品的运费。基本上我有一些我不想收取运费的产品,我把它们归为一个叫做礼物的类别……但我仍然想要一个送货地址。问题是,当我使用我构建的类别过滤器时,它不会按顺序保存地址......如果我只是使用......

add_filter( 'woocommerce_cart_needs_shipping_address', '__return_true', 50 );

效果很好……

但是当我把门放在上面时...它不会保存值...这里是门...

//gifts filter
function HDM_gift_shipping() {
// set our flag to be false until we find a product in that category
$cat_check = false;

// check each cart item for our category
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {

    $product = $cart_item['data'];

   // if cat matches gift return true
    if ( has_term( 'gift', 'product_cat', $product->id ) ) {
        $cat_check = true;
        // break because we only need one "true" to matter here
        break;
    }
}

// if a product in the cart is in our category, do something
if ( $cat_check ) {
    add_filter( 'woocommerce_cart_needs_shipping_address', '__return_true', 50 );
}

}
add_action('woocommerce_before_checkout_billing_form', 'HDM_gift_shipping', 100);

【问题讨论】:

    标签: php wordpress woocommerce field checkout


    【解决方案1】:

    您的代码中有一些错误。为了让它工作,你最好直接在woocommerce_cart_needs_shipping_address过滤钩子中设置你的代码:

    add_filter( 'woocommerce_cart_needs_shipping_address', 'custom_cart_needs_shipping_address', 50, 1 );
    function custom_cart_needs_shipping_address( $needs_shipping_address ) {
        // Loop though cat items
        foreach ( WC()->cart->get_cart() as $cart_item ) {
            if ( has_term( array('gift'), 'product_cat', $cart_item['product_id'] ) ) {
                // Force enable shipping address for virtual "gift" products
                return true; 
            }
        }
        return $needs_shipping_address;
    }
    

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

    在购物车中,要在使用 has_term() WordPress 条件函数时处理 Woocommerce 自定义分类法,如产品类别或标签,您需要使用$cart_item['product_id'] 而不是 $cart_item['data']->get_id(),这不适用于产品变体。

    【讨论】:

    • 再一次带着这个答案来了。听起来你知道你的东西!
    • 最后一个问题,说我想将其限制为标签而不是类别。我可以将 'product_cat' 替换为 'product_tag' 吗?
    • @MattNath 将代码中的分类“product_cat”替换为“product_tag”。
    • 我是这么认为的。再次感谢您!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-09
    • 2013-08-11
    • 1970-01-01
    相关资源
    最近更新 更多