How Can I Hide the Cancel Button if number of items in an order are more than 1

Viewed 120

In My Account > My Orders, I want to "hide" the cancel button if the number of items is greater than 1. I searched but couldn't find a definitive solution. The following code directly disables the cancel state. Therefore, the order cannot be cancelled. I dont want this. I just want to hide the button. An alternative solution would be to add this button to My Account > My Orders > (any Order)(View). However, I couldn't find a solution for this either.

I'd be happy to show you the way. The code I wrote is below:

add_filter('woocommerce_my_account_my_orders_actions', 'remove_my_cancel_button', 10, 2);
function remove_my_cancel_button($actions, $order){
    if ($order->get_item_count() > 1) { 
        unset($actions['cancel']);
    }
    return $actions;
}
1 Answers

In your child theme folder [you should be using a child theme] at wp-content > themes > your_theme_name_here, make a folder called "woocommerce". Then inside that folder, make another folder called "myaccount". This will be how you can override the default WooCommerce plugin files.

Inside that new myaccount folder, you will want to add a copy of the file from the WooCommerce plugin located at wp-content > plugins > woocommerce > templates > myaccount > orders.php

Modify the downloaded orders.php file at line 68 like so:

if ( ! empty( $actions ) ) {
    if ($item_count > 1) {
        foreach ( $actions as $key => $action ) { // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
            echo '<a href="' . esc_url( $action['url'] ) . '" class="woocommerce-button button hide ' . sanitize_html_class( $key ) . '">' . esc_html( $action['name'] ) . '</a>';
        }
    } else {
        foreach ( $actions as $key => $action ) { // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
            echo '<a href="' . esc_url( $action['url'] ) . '" class="woocommerce-button button ' . sanitize_html_class( $key ) . '">' . esc_html( $action['name'] ) . '</a>';
        }
    }
}

What we have done is said, if there is more than 1 item in the order, add a new class in the buttons called "hide".

From there, add a CSS rule like this:

a.woocommerce-button.button.hide.cancel {
    display: none;
}

Here is a link to the whole edited orders.php file in a JSFiddle (please note, I added the code to the HTML window as JSFiddle wasn't created for PHP testing) https://jsfiddle.net/6ks8j50y/

Related