WooCommerce: ubicación adicional de inventario de existencias
Publicado: 2022-12-07El complemento WooCommerce le permite administrar las existencias de cada producto, ¡pero solo tiene un campo de cantidad de existencias!
¿Qué sucede si tiene dos almacenes y, como administrador de la tienda, necesita administrar el inventario para cada ubicación ? Además, ¿qué sucede si un artículo está agotado en la ubicación 1, pero está disponible en la ubicación 2 y, por lo tanto, el cliente necesita poder comprarlo?
Esta sorprendente solución agregará un segundo número de entrada en la configuración del producto, redefinirá la cantidad de existencias y el estado en la interfaz sumando las existencias 1 + las existencias 2, y finalmente disminuirá las existencias 1 hasta que llegue a 0, después de lo cual disminuirá las existencias 2.
Este comportamiento predeterminado se puede cambiar, por supuesto, por ejemplo, es posible definir desde dónde se reduce el stock (¿por distancia?) a través de un código adicional. Además, se puede escribir código adicional para que sea compatible con productos variables o tipos de productos personalizados, así como para que funcione con reembolsos. De cualquier manera, ¡disfrútalo!

Fragmento de PHP: Gestión de la segunda ubicación de existencias
/**
* @snippet Second Stock Location @ WooCommerce Edit Product
* @how-to Get CustomizeWoo.com FREE
* @author Rodolfo Melogli
* @compatible WooCommerce 7
* @donate $9 https://businessbloomer.com/bloomer-armada/
*/
add_action( 'woocommerce_product_options_stock', 'bbloomer_additional_stock_location' );
function bbloomer_additional_stock_location() {
global $product_object;
echo '<div class="show_if_simple show_if_variable">';
woocommerce_wp_text_input(
array(
'id' => '_stock2',
'value' => get_post_meta( $product_object->get_id(), '_stock2', true ),
'label' => '2nd Stock Location',
'data_type' => 'stock',
)
);
echo '</div>';
}
add_action( 'save_post_product', 'bbloomer_save_additional_stock' );
function bbloomer_save_additional_stock( $product_id ) {
global $typenow;
if ( 'product' === $typenow ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
if ( isset( $_POST['_stock2'] ) ) {
update_post_meta( $product_id, '_stock2', $_POST['_stock2'] );
}
}
}
add_filter( 'woocommerce_product_get_stock_quantity' , 'bbloomer_get_overall_stock_quantity', 9999, 2 );
function bbloomer_get_overall_stock_quantity( $value, $product ) {
$value = (int) $value + (int) get_post_meta( $product->get_id(), '_stock2', true );
return $value;
}
add_filter( 'woocommerce_product_get_stock_status' , 'bbloomer_get_overall_stock_status', 9999, 2 );
function bbloomer_get_overall_stock_status( $status, $product ) {
if ( ! $product->managing_stock() ) return $status;
$stock = (int) $product->get_stock_quantity() + (int) get_post_meta( $product->get_id(), '_stock2', true );
$status = $stock && ( $stock > 0 ) ? 'instock' : 'outofstock';
return $status;
}
add_filter( 'woocommerce_payment_complete_reduce_order_stock', 'bbloomer_maybe_reduce_second_stock', 9999, 2 );
function bbloomer_maybe_reduce_second_stock( $reduce, $order_id ) {
$order = wc_get_order( $order_id );
$atleastastock2change = false;
foreach ( $order->get_items() as $item ) {
if ( ! $item->is_type( 'line_item' ) ) {
continue;
}
$product = $item->get_product();
$item_stock_reduced = $item->get_meta( '_reduced_stock', true );
if ( $item_stock_reduced || ! $product || ! $product->managing_stock() ) {
continue;
}
$qty = apply_filters( 'woocommerce_order_item_quantity', $item->get_quantity(), $order, $item );
$stock1 = (int) get_post_meta( $product->get_id(), '_stock', true );
if ( $qty <= $stock1 ) continue;
$atleastastock2change = true;
}
if ( ! $atleastastock2change ) return $reduce;
foreach ( $order->get_items() as $item ) {
if ( ! $item->is_type( 'line_item' ) ) {
continue;
}
$product = $item->get_product();
$item_stock_reduced = $item->get_meta( '_reduced_stock', true );
if ( $item_stock_reduced || ! $product || ! $product->managing_stock() ) {
continue;
}
$item_name = $product->get_formatted_name();
$qty = apply_filters( 'woocommerce_order_item_quantity', $item->get_quantity(), $order, $item );
$stock1 = (int) get_post_meta( $product->get_id(), '_stock', true );
$stock2 = (int) get_post_meta( $product->get_id(), '_stock2', true );
if ( $qty <= $stock1 ) {
wc_update_product_stock( $product, $qty, 'decrease' );
$order->add_order_note( sprintf( 'Reduced stock for item "%s"; Stock 1: "%s" to "%s".', $item_name, $stock1, $stock1 - $qty ) );
} else {
$newstock2 = $stock2 - ( $qty - $stock1 );
wc_update_product_stock( $product, $stock1, 'decrease' );
update_post_meta( $product->get_id(), '_stock2', $newstock2 );
$item->add_meta_data( '_reduced_stock', $qty, true );
$item->save();
$order->add_order_note( sprintf( 'Reduced stock for item "%s"; Stock 1: "%s" to "0" and Stock 2: "%s" to "%s".', $item_name, $stock1, $stock2, $newstock2 ) );
}
}
$order->get_data_store()->set_stock_reduced( $order_id, true );
return false;
}
En inglés simple:

- bbloomer_additional_stock_location muestra el segundo campo de cantidad de existencias
- bbloomer_save_additional_stock guarda la cantidad de stock personalizado
- bbloomer_get_overall_stock_quantity establece el inventario de existencias del producto en existencias 1 + existencias 2
- bbloomer_get_overall_stock_status establece el estado de stock del producto en función del stock 1 + stock 2
- bbloomer_maybe_reduce_second_stock reduce el stock desde el stock 1 y luego desde el stock 2 en caso de que la cantidad pedida sea mayor que el stock 1, de lo contrario, permite que WooCommerce realice la disminución de stock predeterminada