下面的代码自动将产品添加到WooCommerce的购物车中:
add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
if ( ! is_admin() ) {
$product_id = 64;
$found = false;
//check if product already in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->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 )
WC()->cart->add_to_cart( $product_id );
} else {
// if no products in cart, add it
WC()->cart->add_to_cart( $product_id );
}
}
}
答案检查客户是否已经在WooCommerce中购买了某些东西,允许检查用户是否已经使用自定义条件函数has_bought()
.
所以我想要的是检查客户之前是否订购过,并且:
- 如果这是他们的第一次订单,强制产品A进入购物车或
- 如果他们已经做了一次或多次购买,强迫产品B进入购物车
但是我没有找到在我的代码中使用它的方法。
任何帮助都将不胜感激。
下面的代码使用自定义函数has_bought()
。它会自动为新客户和确认客户添加不同的产品:
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 );
}
}
代码放在活动子主题(或活动主题)的functions.php文件中。
相关:检查客户是否已经在WooCommerce中购买了东西