'How to change sorting in WooCommerce "my-account/orders" on button click

I'm trying to add buttons to the "my-account / my orders" tab in the WooCommerce customers frontend view, which change the the sorting order of the customers orders on click.

For days I'm trying to make it work. I guess my approach is wrong, but I have too limited knowledge of PHP and wordpress hooks/logic to find a better solution. Please help!

I have this code in my "functions.php" of my child theme.

Thanks.

add_filter('woocommerce_my_account_my_orders_query', 'my_account_orders_query_change_sorting_DESC' , 20);
function my_account_orders_query_change_sorting_DESC($args)
{
    $args['order'] = 'DESC'; 
    return $args;
}

add_filter('woocommerce_my_account_my_orders_query', 'my_account_orders_query_change_sorting_ASC' , 20);
function my_account_orders_query_change_sorting_ASC($args)
{
    $args['order'] = 'ASC'; 
    return $args;
}
add_action('woocommerce_before_account_orders', 'switch_date' , 20);
function switch_date($has_orders)
{
    if ($has_orders) {
        echo '<form method="post">
        <input type="submit" name="button1"
                value="ASC" />
          
        <input type="submit" name="button2"
                value="DESC" />
        </form>';
    }
    if (isset($_POST['button1'])) 
    {
        apply_filters('woocommerce_my_account_my_orders_query', 'my_account_orders_query_change_sorting_ASC' , 20); 
    }
    else if(isset($_POST['button2'])) 
    {
        apply_filters('woocommerce_my_account_my_orders_query', 'my_account_orders_query_change_sorting_DESC' , 20); 
    } 
}


Solution 1:[1]

I solved it. :) The problem was i didn't understand the order in which the site is loaded. Two hooks are unnecessary and overwrite each other. apply_filters() is unnecessary. This works like a charm:

add_action('woocommerce_before_account_orders', 'add_resort_form');
function add_resort_form($has_orders)
{   
    if ($has_orders) {
        echo '<form method="post">
        <input type="submit" name="button1"
                value="ASC" />          
        <input type="submit" name="button2"
                value="DESC" />
        </form>';
    }
}

add_filter('woocommerce_my_account_my_orders_query', 'my_account_orders_query_change_sorting');
function my_account_orders_query_change_sorting($args)
{
    if (isset($_POST['button1'])) {
        $value = 'ASC';
    }
    else if(isset($_POST['button2'])) {
        $value = 'DESC';    
    }
    $args['order'] = $value; 
    return $args;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1