Разрешить клиенту удалять позиции заказа в Woocommerce - PullRequest
1 голос
/ 28 апреля 2019

привет, у меня есть этот код, который должен удалить элемент из заказа

    add_action( 'woocommerce_order_item_meta_end', 'display_remove_order_item_button', 10, 3 );
function display_remove_order_item_button( $item_id, $item, $order ){
    // Avoiding displaying buttons on email notification
    if( ! ( is_wc_endpoint_url( 'view-order' ) || is_wc_endpoint_url( 'order-received' ) ) ) return;

    if( isset($_POST["remove_item_$item_id"]) && $_POST["remove_item_$item_id"] == 'Remove this item' ){
        wc_delete_order_item( $item_id );
        $order->calculate_totals();

    }

    echo '<form class="cart" method="post" enctype="multipart/form-data" style= "margin-top:12px;">
    <input type="submit" class="button" name="remove_item_'.$item_id.'" value="Complete Cancellation" />
    </form>';
}

enter image description here

Но когда я нажимаю полное обновление страницы отменыно ничего не удаляется и я снова обновляю ничего не удаляется

что я делаю не так?

1 Ответ

1 голос
/ 28 апреля 2019

В вашем коде есть несколько ошибок, таких как:

  • условие $_POST["remove_item_$item_id"] == 'Remove this item' всегда ложно.
  • Вам нужно удалить элемент, используя хук перед загрузкой страницы, чтобы получить обновление. Если нет, вы не увидите, что элемент был удален, и вам нужно будет перезагрузить страницу один раз.

Поэтому попробуйте следующее:

// Displaying the form fields (buttons and hidden fields)
add_action( 'woocommerce_order_item_meta_end', 'display_remove_order_item_button', 10, 3 );
function display_remove_order_item_button( $item_id, $item, $order ){
    // Avoiding displaying buttons on email notification
    if( ! ( is_wc_endpoint_url( 'view-order' ) || is_wc_endpoint_url( 'order-received' ) ) )
        return;

    echo '<form class="cart item-'.$item_id.'" method="post" style= "margin-top:12px;">
    <input type="hidden" name="item_id" value="'.$item_id.'" />
    <input type="hidden" name="order_id" value="'.$order->get_id().'" />
    <input type="submit" class="button" name="remove_item_'.$item_id.'" value="Complete Cancellation" />
    </form>';
}

// Processing the request
add_action( 'template_redirect', 'process_remove_order_item' );
function process_remove_order_item(){
    // Avoiding displaying buttons on email notification
    if( ! ( is_wc_endpoint_url( 'view-order' ) || is_wc_endpoint_url( 'order-received' ) ) )
        return;

    if( isset($_POST['item_id']) && isset($_POST['remove_item_'.$_POST['item_id']]) && isset($_POST['order_id'])
    && is_numeric($_POST['order_id']) && get_post_type($_POST['order_id']) === 'shop_order' ) {
        // Get the WC_Order Object
        $order = wc_get_order( absint($_POST['order_id']) );

        // Remove the desired order item
        if( is_a($order, 'WC_Order') && is_numeric($_POST['item_id']) ) {
            $order->remove_item( absint($_POST['item_id']) );
            $order->calculate_totals();

            // Optionally display a notice
            wc_add_notice( __('Order item removed successfully'), 'success' );
        }

    }
}

Код помещается в файл function.php вашей активной дочерней темы (или активной темы). Проверено и работает.

enter image description here

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