skip to Main Content

I recently upgraded a Woocommerce website to use HPOS and I found out the custom column sorting no longer works. In Woocommerce I setup a sortable column for a customers last name. I adjusted my code to use meta_query to sort orders based on _shipping_last_name but no results are returned. I have a column that shows the correct last name value, but the sort feature doesn’t sort.

Here is the sorting code currently:

function hpos_args( $query_vars ) {

    if(isset($query_vars['orderby']) && $query_vars['orderby'] == 'customer_user'){
        $query_vars['meta_query'] = array(array(    'key' => '_shipping_last_name' ));
        $query_vars['orderby'] = array('meta_value' => $query_vars['order']);
    }

    return $query_vars;
}
add_filter( 'woocommerce_order_query_args', 'hpos_args', 10, 1 );

‘customer_user’ is the column title, the values in the column are the meta_value for _shipping_last_name

2

Answers


  1. Chosen as BEST ANSWER

    I did as @LoicTheAztec suggested and created custom metadata for the shipping last name. I then was able to sort the column with the following code:

    function hpos_args( $query_vars ) {
    
        $query_vars['meta_query'] = array(array(    'key' => '_sorting_name' ));
        $query_vars['orderby'] = array('meta_value' => $query_vars['order']);
    
        return $query_vars;
    }
    
    add_filter( 'woocommerce_order_query_args', 'hpos_args', 10, 1 );
    

    I was having issues using the key name _shipping_last_name so went with _sorting_name.


  2. When you have only one meta key, simply use "meta_key" query argument instead.

    Also, you need to target "customer_user" order_by query string argument like:

    // Define custom sortable column(s)
    add_filter( "woocommerce_shop_order_list_table_sortable_columns", 'custom_admin_order_list_sortable_columns' );
    function custom_admin_order_list_sortable_columns( $sortable_columns ) {
        $sortable_columns['customer_user'] = 'customer_user';
    
        return $customer_user;
    }
    
    // Alter the query for custom sortable column(s)
    add_filter( 'woocommerce_order_query_args', 'filter_admin_hpos_order_lists', 10, 1 );
    function filter_admin_hpos_order_lists( $query_vars ) {
        if ( isset($_GET['orderby']) && $_GET['orderby'] === 'customer_user' ) {
            $query_vars['meta_key'] = '_sorting_name';
            $query_vars['orderby'] = array('meta_value' => $query_vars['order']);
        }
        return $query_vars;
    }
    

    Code goes in functions.php file of your child theme (or in a plugin). Tested and works.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search