Php 允许根据WooCommerce中的购物车总数向购物车添加特定产品

Php 允许根据WooCommerce中的购物车总数向购物车添加特定产品,php,wordpress,woocommerce,cart,product,Php,Wordpress,Woocommerce,Cart,Product,在woocommerce中,我试图找到一种方法,仅当达到特定购物车总金额时,才允许将产品添加到购物车中 示例:我们想以1美元的价格出售保险杠贴纸,但前提是用户已经在购物车中购买了价值25美元的其他产品。这类似于亚马逊的“附加”功能。但是我找不到类似的WooCommerce插件或函数 我已经尝试了一些代码,但没有成功…如果有任何帮助,我将不胜感激。可以使用woocommerce\u add\u to\u cart\u validationfilter hook中的自定义函数来完成,您将在其中定义:

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

示例:我们想以1美元的价格出售保险杠贴纸,但前提是用户已经在购物车中购买了价值25美元的其他产品。这类似于亚马逊的“附加”功能。但是我找不到类似的WooCommerce插件或函数


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

可以使用
woocommerce\u add\u to\u cart\u validation
filter hook中的自定义函数来完成,您将在其中定义:

  • 一个产品Id(或多个产品Id)
  • 要达到的阈值购物车金额
在达到特定购物车金额之前,将避免将这些已定义的产品添加到购物车(显示自定义通知)

守则:

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;
}
add_过滤器('woocommerce_add_to_cart_validation','wc_add_on_feature',20,3);
函数wc\u添加功能($passed,$product\u id,$quantity){
//此处定义此阵列中的一个或多个产品ID
$products\U ids=阵列(37,27);
//此处定义需要达到的最低购物车数量
$amount_阈值=25;
//折扣后购物车中的项目总数
$cart\u amount=WC()->cart->get\u cart\u contents\u total();
//状况
if($cart\u amount<$amount\u threshold&&in\u数组($product\u id,$products\u id)){
$passed=false;
$text_notice=uuuu(“购物车金额需要高达$25才能添加此产品”,“woocommerce”);
wc_add_notice($text_notice,'error');
}
返回$passed;
}
代码进入活动子主题(活动主题)的function.php文件

测试和工作