根据WooCommerce中的购物车总数,允许添加到特定产品的购物车 [英] Allow add to cart for specific products based on cart total in WooCommerce

查看:61
本文介绍了根据WooCommerce中的购物车总数,允许添加到特定产品的购物车的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在woocommerce中,我试图找到一种方法,仅在达到特定购物车总金额时才允许将产品添加到购物车中.

In woocommerce, I am trying to find a way to only allow a product to be added a to cart only when a specific cart total amount is reached.

示例:我们希望以 $ 1 的价格出售保险杠,但前提是用户已经有价值 $ 25 的其他产品购物车.这类似于亚马逊的附加"功能.但是我找不到类似的WooCommerce插件或功能.

Example: We want to sell a bumper sticker for $1, but only if a user already has $25 worth of other products already in the cart. This is similar to Amazon's "add on" feature. However I can't find a similar WooCommerce plugin or function.

我已经尝试了一些代码,但是没有成功……任何帮助将不胜感激.

I have tried yet some code without success… Any help will be appreciated.

推荐答案

可以使用连接在 woocommerce_add_to_cart_validation 过滤器挂钩中的自定义函数来完成,您将在其中定义:

Can be done with a custom function hooked in woocommerce_add_to_cart_validation filter hook, where you will define:

  • 一个产品ID(或多个产品ID).
  • 要达到的购物车最低金额.

在达到特定的购物车数量之前,将避免将已定义的产品添加到购物车(显示自定义通知).

It will avoid for those defined products to be added to cart (displaying a custom notice) until that specific cart amount is reached.

代码:

add_filter( 'woocommerce_add_to_cart_validation', 'wc_add_on_feature', 20, 3 );
function wc_add_on_feature( $passed, $product_id, $quantity ) {

    // HERE define one or many products IDs in this array
    $products_ids = array( 37, 27 );

    // HERE define the minimal cart amount that need to be reached
    $amount_threshold = 25;

    // Total amount of items in the cart after discounts
    $cart_amount = WC()->cart->get_cart_contents_total();

    // The condition
    if( $cart_amount < $amount_threshold && in_array( $product_id, $products_ids ) ){
        $passed = false;
        $text_notice = __( "Cart amount need to be up to $25 in order to add this product", "woocommerce" );
        wc_add_notice( $text_notice, 'error' );
    }
    return $passed;
}

代码进入您的活动子主题(活动主题)的function.php文件中.

经过测试,可以正常工作.

Tested and works.

这篇关于根据WooCommerce中的购物车总数,允许添加到特定产品的购物车的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆