我需要woocommerce自动恢复库存quanitiy挂钩订单退款 请关于此的任何一个帮助 我尝试了2个钩子
add_action( 'woocommerce_product_set_stock','action_woocommerce_variation_set_stock', 10, 1 );
add_action( 'woocommerce_variation_set_stock', 'action_woocommerce_variation_set_stock', 10, 1 );
但是当产品库存数量按订单减少时,这些钩子会在前端工作
请解决此问题
答案 0 :(得分:0)
尝试使用以下操作挂钩:
add_action( 'woocommerce_order_status_processing_to_refunded', 'YOUR_ACTION_NAME', 10, 1 );
add_action( 'woocommerce_order_status_completed_to_refunded', 'YOUR_ACTION_NAME', 10, 1 );
add_action( 'woocommerce_order_status_on-hold_to_refunded', 'YOUR_ACTION_NAME', 10, 1 );
add_action( 'woocommerce_order_status_processing_to_refunded', 'YOUR_ACTION_NAME', 10, 1 );
add_action( 'woocommerce_order_status_completed_to_refunded', 'YOUR_ACTION_NAME', 10, 1 );
add_action( 'woocommerce_order_status_on-hold_to_refunded', 'YOUR_ACTION_NAME', 10, 1 );
add_action( 'woocommerce_order_status_failed_to_refunded', 'YOUR_ACTION_NAME', 10, 1 );
function YOUR_ACTION_NAME( $order_id ) {
$order = new WC_Order( $order_id );
if ( ! get_option('woocommerce_manage_stock') == 'yes' && ! sizeof( $order->get_items() ) > 0 ) {
return;
}
foreach ( $order->get_items() as $item ) {
if ( $item['product_id'] > 0 ) {
$_product = $order->get_product_from_item( $item );
if ( $_product && $_product->exists() && $_product->managing_stock() ) {
$old_stock = $_product->stock;
$qty = apply_filters( 'woocommerce_order_item_quantity', $item['qty'], $this, $item );
$new_quantity = $_product->increase_stock( $qty );
do_action( 'woocommerce_auto_stock_restored', $_product, $item );
$order->add_order_note( sprintf( __( 'Item #%s stock incremented from %s to %s.', 'woocommerce' ), $item['product_id'], $old_stock, $new_quantity) );
$order->send_stock_notifications( $_product, $new_quantity, $item['qty'] );
}
}
}
} //End of function
将 YOUR_ACTION_NAME 替换为您自己的函数名称。
答案 1 :(得分:0)
这是我的代码:
/**
* WooCommerce - do a custom action on order status change
*/
function jasom_custom_actions_on_order_status_change( $order_id, $checkout = null ) {
$order = new WC_Order( $order_id );
if (!get_option( 'woocommerce_manage_stock' ) == 'yes' && !sizeof( $order->get_items() ) > 0) {
return;
}
if ($order->get_status() === 'refunded') {
$changes = [];
foreach ($order->get_items() as $item) {
if ($item[ 'product_id' ] > 0) {
$product = $item->get_product();
if ($product && $product->exists() && $product->managing_stock()) {
$qty = $item->get_quantity(); // Get the item quantity
$new_quantity = $product->increase_stock( $qty );
do_action( 'woocommerce_auto_stock_restored', $product, $item );
$changes[] = $product->get_formatted_name() . ' ' . ( $new_quantity - $qty ) . '→' . $new_quantity;
$order->send_stock_notifications( $product, $new_quantity, $item[ 'qty' ] );
}
}
}
if ($changes) {
$order->add_order_note( __( 'Stock levels increased:', 'woocommerce' ) . ' ' . implode( ', ', $changes ) );
}
}
}
add_action( 'woocommerce_order_status_changed', 'jasom_custom_actions_on_order_status_change' );