WooCommerce在添加之前检查产品ID的库存

use*_*227 3 php wordpress product cart woocommerce

我在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();
        }
    } 
}
Run Code Online (Sandbox Code Playgroud)

}

Loi*_*tec 5

您可以直接在if语句中使用WC_Product条件方法 is_in_stock()

正如$product已经是一个产品对象,我们不需要其他任何东西就可以使其与WC_product方法一起使用

此外,而不是使用sizeof( WC()->cart->get_cart() ) > 0您可以通过WC_cart方法代替is_empty()这种方式! WC()->cart->is_empty()

然后,您也可以sizeof( WC()->cart->get_cart() ) == 1使用WC_cart get_cart_contents_count()方法进行替换WC()->cart->get_cart_contents_count() == 1

你不再需要的global woocommerce;,如果你使用的声明WC()->cart,而不是$woocommerce->cart所有WC_Cart方法

最后一件事:
最好删除相关的购物车物品,而不是清空购物车。因此,我们将使用remove_cart_item()method代替。
如果不方便,您可以使用empty_cart()原始代码中的方法...

因此您的代码将是:

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 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();
            }
        }
    } 
}
Run Code Online (Sandbox Code Playgroud)

此代码已经过测试并且可以工作。

代码进入您的活动子主题(或主题)的function.php文件中。或在任何插件php文件中。