WC_Cart::check_cart_item_stock()publicWC 1.0

Looks through the cart to check each item is in stock. If not, add an error.

Method of the class: WC_Cart{}

Return

true|false|WP_Error.

Usage

$WC_Cart = new WC_Cart();
$WC_Cart->check_cart_item_stock();

WC_Cart::check_cart_item_stock() code WC 9.4.2

public function check_cart_item_stock() {
	$error                    = new WP_Error();
	$product_qty_in_cart      = $this->get_cart_item_quantities();
	$current_session_order_id = isset( WC()->session->order_awaiting_payment ) ? absint( WC()->session->order_awaiting_payment ) : absint( WC()->session->get( 'store_api_draft_order', 0 ) );

	foreach ( $this->get_cart() as $values ) {
		$product = $values['data'];

		// Check stock based on stock-status.
		if ( ! $product->is_in_stock() ) {
			/* translators: %s: product name */
			$error->add( 'out-of-stock', sprintf( __( 'Sorry, "%s" is not in stock. Please edit your cart and try again. We apologize for any inconvenience caused.', 'woocommerce' ), $product->get_name() ) );
			return $error;
		}

		// We only need to check products managing stock, with a limited stock qty.
		if ( ! $product->managing_stock() || $product->backorders_allowed() ) {
			continue;
		}

		// Check stock based on all items in the cart and consider any held stock within pending orders.
		$held_stock     = wc_get_held_stock_quantity( $product, $current_session_order_id );
		$required_stock = $product_qty_in_cart[ $product->get_stock_managed_by_id() ];

		/**
		 * Allows filter if product have enough stock to get added to the cart.
		 *
		 * @since 4.6.0
		 * @param bool       $has_stock If have enough stock.
		 * @param WC_Product $product   Product instance.
		 * @param array      $values    Cart item values.
		 */
		if ( apply_filters( 'woocommerce_cart_item_required_stock_is_not_enough', $product->get_stock_quantity() < ( $held_stock + $required_stock ), $product, $values ) ) {
			/* translators: 1: product name 2: quantity in stock */
			$error->add( 'out-of-stock', sprintf( __( 'Sorry, we do not have enough "%1$s" in stock to fulfill your order (%2$s available). We apologize for any inconvenience caused.', 'woocommerce' ), $product->get_name(), wc_format_stock_quantity_for_display( $product->get_stock_quantity() - $held_stock, $product ) ) );
			return $error;
		}
	}

	return true;
}