php - 在 Woocommerce 购物车中自动添加或删除免费产品,但在购物车中不包含订阅产品
问题描述
您好,这是与下面的链接类似的问题,但只是想问一下,如果购买的产品是订阅类型,是否可以设置不加载免费产品的条件?谢谢你。 在 Woocommerce 购物车中自动添加或删除免费产品
/**
* Add another product depending on the cart total
*/
add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
if ( ! is_admin() ) {
global $woocommerce;
$product_id = 85942; //replace with your product id
$found = false;
$cart_total = 15; //replace with your cart total needed to add above item
if( $woocommerce->cart->total >= $cart_total ) {
//check if product already in cart
if ( sizeof( $woocommerce->cart->get_cart() ) > 0 ) {
$isVirtualOnly = false;
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values) {
$_product = $values[‘data’];
if ($_product != null)
if ($_product->get_type() != $_virtual)
$isVirtualOnly = false;
}
if ($isVirtualOnly != true) {
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->get_id() == $product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
$woocommerce->cart->add_to_cart( $product_id );
}
} else {
// if no products in cart, add it
$woocommerce->cart->add_to_cart( $product_id );
}
}
}
}
/**
* END Add another product depending on the cart total
*/
解决方案
add_action( 'template_redirect', 'add_product_to_cart_conditionally' );
function add_product_to_cart_conditionally() {
if ( is_admin() ) return; // Exit
// Below define the product Id to be added:
$product_A = 37; // <== For new customers that have not purchased a product before (and guests)
$product_B = 53; // <== For confirmed customers that have purchased a product before
$product_id = has_bought() ? $product_B : $product_A;
// If cart is empty
if( WC()->cart->is_empty() ) {
WC()->cart->add_to_cart( $product_id ); // Add the product
}
// If cart is not empty
else {
// Loop through cart items (check cart items)
foreach ( WC()->cart->get_cart() as $item ) {
// Check if the product is already in cart
if ( $item['product_id'] == $product_id ) {
return; // Exit if the product is in cart
}
}
// The product is not in cart: We add it
WC()->cart->add_to_cart( $product_id );
}
}
推荐阅读
- python - 为什么这个函数不返回任何输出而只使用打印?
- ajax - Laravel 中的 AJAX POST 请求说找不到 url
- android - 如何将 sklearn 模型嵌入手机以供离线使用?
- ios - 在笔记本电脑睡眠期间运行 applescript 以错误结束
- visual-studio-code - 如何在 VSCode 1.55+ 中关闭窗口标题 git 编辑状态
- android - 如何从 Firebase Cloud Functions 上传文本文件?
- visual-studio-2019 - C# & Visual Studio:存储问题
- node.js - 云函数中的参数未定义
- javascript - 如何将月份转换为单词而不是reactJs中的数字?
- html - 如何在 CSS 中定位滚动而不考虑它的块