【问题标题】:Hiding coupon field in cart for a product category在购物车中隐藏产品类别的优惠券字段
【发布时间】:2017-01-11 15:12:25
【问题描述】:

我试图隐藏购物车中一些排除产品的优惠券代码字段。我添加了一个产品类别,并从优惠券使用中排除了这个类别。

sn-p 限制购物车,因此一次只允许一件产品。在这种情况下,无需显示排除产品的优惠券代码。验证不会让用户应用优惠券,但如果他们甚至没有看到优惠券字段会更好。

这是我发现的一个sn-p,它找到一个产品类别并显示一条消息:

// Find product category
add_action( 'woocommerce_check_cart_items', 'checking_cart_items', 12 );
function checking_cart_items() {
// set your special category name, slug or ID here:
$special_cat = 'myproductcategory';
$bool = false;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
    $item = $cart_item['data'];
    if ( has_term( $special_cat, 'product_cat', $item->id ) )
        $bool = true;
}
// Displays a message if category is found
if ($bool)
    echo '<div class="checkoutdisc">A custom message displayed.</div>';

}

这是在购物车中隐藏优惠券代码的通用sn-p:

// hide coupon field on cart page
function hide_coupon_field_on_cart( $enabled ) {

if ( is_cart() ) {
    $enabled = false;
}

return $enabled;
}
add_filter( 'woocommerce_coupons_enabled', 'hide_coupon_field_on_cart' );

如何让这些功能协同工作?

谢谢

【问题讨论】:

    标签: php wordpress woocommerce categories cart


    【解决方案1】:

    更新:与 WooComerce 3+ 的兼容性

    是的,可以使用以下代码组合:

    add_filter( 'woocommerce_coupons_enabled', 'conditionally_hide_cart_coupon_field' );
    function conditionally_hide_cart_coupon_field( $enabled ) {
        // Set your special category name, slug or ID here:
        $special_cat = array('clothing');
        $bool = false;
    
        foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
            $wc_product = $cart_item['data'];
            // Woocommerce compatibility
            $product_id = method_exists( $wc_product, 'get_id' ) ? $wc_product->get_id() : $wc_product->id;
    
            $main_product_id = $cart_item['variation_id'] > 0 ? $cart_item['product_id'] : $product_id;
            if ( has_term( $special_cat, 'product_cat', $main_product_id ) )
                $bool = true;
        }
    
        if ( $bool && is_cart() ) {
            $enabled = false;
        }
        return $enabled;
    }
    

    当然,这会出现在您活动的子主题(或主题)的 function.php 文件中,也可以出现在任何插件文件中。

    此代码已经过测试并且可以工作。


    参考资料:

    【讨论】:

    • 还有一件事。我怎么能隐藏我在购物车中显示的相同条件的 div。在这种情况下可能隐藏的优惠券的一些说明。
    • 抱歉,错过了。现在修好了。
    • 购物车页面以一些说明开始,告诉用户优惠券代码的工作原理。我正在使用我的主题中的页面构建块。所以这不是 WooCommerce 添加的元素。这是一个可以使用 display:none 隐藏的 div,但前提是使用此产品类别。
    • @Dudikowski 在聊天中看……你有关于的信息。
    • @LoicTheAztec 这段代码阻止我访问“wp-admin”,它不允许我访问,你知道为什么吗?
    猜你喜欢
    • 2019-01-12
    • 2021-10-18
    • 2013-11-28
    • 1970-01-01
    • 2018-08-10
    • 2021-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多