【发布时间】:2021-05-29 08:46:04
【问题描述】:
以下代码在 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 );
}
}
}
答案Checking if customer has already bought something in WooCommerce 允许使用自定义条件函数has_bought() 检查用户是否已经购买。
所以我想要检查客户之前是否订购过并且:
- 如果这是他们的第一个订单,请将产品 A 强制放入购物车或
- 如果他们已经购买了一次或多次,则强制产品 B 进入 购物车
但我没有找到在我的代码中使用它的方法。
任何帮助将不胜感激。
【问题讨论】:
标签: php wordpress woocommerce product cart