wc_restock_refunded_items()WC 3.0.0

Restock items during refund.

Return

null. Nothing.

Usage

wc_restock_refunded_items( $order, $refunded_line_items );
$order(WC_Order) (required)
Order instance.
$refunded_line_items(array) (required)
Refunded items list.

Changelog

Since 3.0.0 Introduced.

Code of wc_restock_refunded_items() WC 6.8.2

function wc_restock_refunded_items( $order, $refunded_line_items ) {
	if ( ! apply_filters( 'woocommerce_can_restock_refunded_items', true, $order, $refunded_line_items ) ) {
		return;
	}

	$line_items = $order->get_items();

	foreach ( $line_items as $item_id => $item ) {
		if ( ! isset( $refunded_line_items[ $item_id ], $refunded_line_items[ $item_id ]['qty'] ) ) {
			continue;
		}
		$product                = $item->get_product();
		$item_stock_reduced     = $item->get_meta( '_reduced_stock', true );
		$restock_refunded_items = (int) $item->get_meta( '_restock_refunded_items', true );
		$qty_to_refund          = $refunded_line_items[ $item_id ]['qty'];

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

		$old_stock = $product->get_stock_quantity();
		$new_stock = wc_update_product_stock( $product, $qty_to_refund, 'increase' );

		// Update _reduced_stock meta to track changes.
		$item_stock_reduced = $item_stock_reduced - $qty_to_refund;

		// Keeps track of total running tally of reduced stock.
		$item->update_meta_data( '_reduced_stock', $item_stock_reduced );

		// Keeps track of only refunded items that needs restock.
		$item->update_meta_data( '_restock_refunded_items', $qty_to_refund + $restock_refunded_items );

		/* translators: 1: product ID 2: old stock level 3: new stock level */
		$restock_note = sprintf( __( 'Item #%1$s stock increased from %2$s to %3$s.', 'woocommerce' ), $product->get_id(), $old_stock, $new_stock );

		/**
		 * Allow the restock note to be modified.
		 *
		 * @since 6.4.0
		 *
		 * @param string $restock_note The original note.
		 * @param int $old_stock The old stock.
		 * @param bool|int|null $new_stock The new stock.
		 * @param WC_Order $order The order the refund was done for.
		 * @param bool|WC_Product $product The product the refund was done for.
		 */
		$restock_note = apply_filters( 'woocommerce_refund_restock_note', $restock_note, $old_stock, $new_stock, $order, $product );

		$order->add_order_note( $restock_note );

		$item->save();

		do_action( 'woocommerce_restock_refunded_item', $product->get_id(), $old_stock, $new_stock, $order, $product );
	}
}