wc_reduce_stock_levels()WC 3.0.0

Reduce stock levels for items within an order, if stock has not already been reduced for the items.

Возвращает

null. Ничего (null).

Использование

wc_reduce_stock_levels( $order_id );
$order_id(int|WC_Order) (обязательный)
Order ID or order instance.

Список изменений

С версии 3.0.0 Введена.

Код wc_reduce_stock_levels() WC 9.3.3

function wc_reduce_stock_levels( $order_id ) {
	if ( is_a( $order_id, 'WC_Order' ) ) {
		$order    = $order_id;
		$order_id = $order->get_id();
	} else {
		$order = wc_get_order( $order_id );
	}
	// We need an order, and a store with stock management to continue.
	if ( ! $order || 'yes' !== get_option( 'woocommerce_manage_stock' ) || ! apply_filters( 'woocommerce_can_reduce_order_stock', true, $order ) ) {
		return;
	}

	$changes = array();

	// Loop over all items.
	foreach ( $order->get_items() as $item ) {
		if ( ! $item->is_type( 'line_item' ) ) {
			continue;
		}

		// Only reduce stock once for each item.
		$product            = $item->get_product();
		$item_stock_reduced = $item->get_meta( '_reduced_stock', true );

		if ( $item_stock_reduced || ! $product || ! $product->managing_stock() ) {
			continue;
		}

		/**
		 * Filter order item quantity.
		 *
		 * @param int|float             $quantity Quantity.
		 * @param WC_Order              $order    Order data.
		 * @param WC_Order_Item_Product $item Order item data.
		 */
		$qty       = apply_filters( 'woocommerce_order_item_quantity', $item->get_quantity(), $order, $item );
		$item_name = $product->get_formatted_name();
		$new_stock = wc_update_product_stock( $product, $qty, 'decrease' );

		if ( is_wp_error( $new_stock ) ) {
			/* translators: %s item name. */
			$order->add_order_note( sprintf( __( 'Unable to reduce stock for item %s.', 'woocommerce' ), $item_name ) );
			continue;
		}

		$item->add_meta_data( '_reduced_stock', $qty, true );
		$item->save();

		$change    = array(
			'product' => $product,
			'from'    => $new_stock + $qty,
			'to'      => $new_stock,
		);
		$changes[] = $change;

		/**
		 * Fires when stock reduced to a specific line item
		 *
		 * @param WC_Order_Item_Product $item Order item data.
		 * @param array $change  Change Details.
		 * @param WC_Order $order  Order data.
		 * @since 7.6.0
		 */
		do_action( 'woocommerce_reduce_order_item_stock', $item, $change, $order );
	}

	wc_trigger_stock_change_notifications( $order, $changes );

	do_action( 'woocommerce_reduce_order_stock', $order );
}