我的 WooCommerce 网站中有一些自定义代码,用于将产品添加到用户购物车。我已经让它检查购物车内容以确保购物车中首先有另一种产品,但我还希望它检查正在添加的产品是否也有库存...
我想不出最好的方法。如果您能让我知道要向函数中添加什么以使其检查“product_id”的库存以及库存是否 > 0,我将不胜感激。这是我的代码:
add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
if ( ! is_admin() ) {
$product_id = 21576;
$found = false;
global $woocommerce;
//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->id == $product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
WC()->cart->add_to_cart( $product_id );
if (sizeof( WC()->cart->get_cart() ) == 1 && $found == true ) {
$woocommerce->cart->empty_cart();
}
}
}
最佳答案
You can use the WC_Product conditional method
is_in_stock()
directly in your if statement.As
$product
is already a product object, we don't need anything else to make it work with WC_product methods.
也可以使用 WC_cart 方法 is_empty()
代替 sizeof( WC()->cart->get_cart() ) > 0
这样! WC()->购物车->is_empty()
。
然后您还可以使用 WC_cart get_cart_contents_count()
替换 sizeof( WC()->cart->get_cart() ) == 1
这种方法 WC()->cart->get_cart_contents_count() == 1
。
如果您使用 WC()->cart
global woocommerce;
声明> 用 all WC_Cart methods 代替 $woocommerce->cart
Last thing:
May be is better to remove the concerned cart item, instead emptying the cart. So we will useremove_cart_item()
method instead.
If is not convenient you can useempty_cart()
method as in your original code…
所以你的代码将是:
add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
if ( ! is_admin() ) {
$targeted_product_id = 21576;
$found = false;
//check if product already in cart
if ( ! WC()->cart->is_empty() ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product = $cart_item['data'];
if ( $product->id == $targeted_product_id ) {
$found = true;
break; // We can break the loop
}
}
// Update HERE (we generate a new product object $_product)
$_product = wc_get_product( $targeted_product_id );
// If product is not in the cart items AND IT IS IN STOCK
if ( !$found && $_product->is_in_stock() ) {
WC()->cart->add_to_cart( $targeted_product_id );
}
elseif ( $found && WC()->cart->get_cart_contents_count() == 1 ) {
// Removing only this cart item
WC()->cart->remove_cart_item( $cart_item_key );
// WC()->cart->empty_cart();
}
}
}
}
此代码已经过测试并且可以工作。
代码位于您的事件子主题(或主题)的 function.php 文件中。或者也可以在任何插件 php 文件中。
关于php - WooCommerce 在添加之前检查产品 ID 的库存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41148592/