Остановить WooCommerce для сокращения запасов на заброшенный новый заказ администратора - PullRequest
1 голос
/ 20 сентября 2019

Если администратор отправляется на создание заказа, но отказывается от него, уровень запасов по-прежнему уменьшается.

Шаги для воспроизведения:

  1. установка WordPress
  2. установкаWooCommerce
  3. создайте простой продукт и отметьте "управлять запасами?"и установите уровень запаса на 10
  4. просмотр на внешнем интерфейсе (см. скриншот before.png)
  5. , поскольку администратор создает новый заказ, но не сохраняет его (новый -> заказ -> добавить элемент-> Выход со страницы)
  6. просмотр во внешней части (см. скриншот after.png)
  7. Обратите внимание, что уровень запасов был уменьшен, даже если этот заказ не был сохранен.

Есть ли способ избежать этого?

Before.png: before.png

After.png after.png

1 Ответ

0 голосов
/ 20 сентября 2019

Я работал над этой проблемой и написал для нее базовый код.

Используемые крючки:"woocommerce_order_item_add_action_buttons" для элемента (ов) Add Order (s) и "woocommerce_process_shop_order_meta" для заказа администратораСоздание / обновление.

Первая часть: Прекратить сокращение запасов товаров, которые были добавлены, пока заказ не был создан.

// define the woocommerce_order_item_add_action_buttons callback 
function action_woocommerce_order_item_add_action_buttons( $order ) { 
    $orderID = $order->ID;
    //check if this is the admin manual order creation 
    if(get_post_status($orderID) == "auto-draft" && get_post_type($orderID) == "shop_order")
    {
        foreach( $order->get_items() as $item_id => $item )
        {
            $product_id = $item->get_product_id();
            $variation_id = $item->get_variation_id();
            $product_quantity = $item->get_quantity();

            if($variation_id == 0)
            {
                $product = wc_get_product($product_id);
                wc_update_product_stock($product, $product_quantity, 'increase');
            }
            else
            {
                $variation = wc_get_product($variation_id);
                wc_update_product_stock($variation, $product_quantity, 'increase' );
            }

            // The text for the note
            $note = __("Stock incremented due to the auto draft post type. Stock for each item will be decremented when this order created.");
            // Add the note
            $order->add_order_note( $note );
        }
    }
}; 

// add the action 
add_action( 'woocommerce_order_item_add_action_buttons', 'action_woocommerce_order_item_add_action_buttons', 10, 1 );

Вторая часть: Уменьшить запас товаров, которые добавляются при создании заказа.

add_action( 'woocommerce_process_shop_order_meta', 'woocommerce_process_shop_order', 10, 2 );
function woocommerce_process_shop_order ( $post_id, $post ) {
    $order = wc_get_order( $post_id );

    //check if this is order create action, not an update action
    if(get_post_status($post_id) == "draft" && get_post_type($post_id) == "shop_order")
    {
        foreach( $order->get_items() as $item_id => $item )
        {
            $product_id = $item->get_product_id();
            $variation_id = $item->get_variation_id();
            $product_quantity = $item->get_quantity();

            if($variation_id == 0)
            {
                $product = wc_get_product($product_id);
                wc_update_product_stock($product, $product_quantity, 'decrease');
            }
            else
            {
                $variation = wc_get_product($variation_id);
                wc_update_product_stock($variation, $product_quantity, 'decrease' );
            }

            // The text for the note
            $note = __("Stock decremented for all items in this order.");
            // Add the note
            $order->add_order_note( $note );
    }
    }
}

Протестировано и работает нормально.Я надеюсь, что это поможет вам.Хорошего дня.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...