I am trying to sort all my orders in alphabetical order in a custom column that I have built. Right now it can only be sorted asc and desc by the time when order was created.
I have built a custom column for user last name, I have passed billing last name inside that column.
Right now I am tryin to make it sort in alphabetical order. I am using the following:
function add_order_new_column_header( $columns ) {
$new_columns = array();
foreach ( $columns as $column_name => $column_info ) {
$new_columns[ $column_name ] = $column_info;
if ( 'order_total' === $column_name ) {
$new_columns['billing_info'] = __( 'Billing Info', 'my-textdomain' );
}
}
return $new_columns;
}
add_filter( 'manage_edit-shop_order_columns', 'add_order_new_column_header', 20);
add_action( 'manage_shop_order_posts_custom_column', 'add_wc_order_admin_list_column_content' );
function add_wc_order_admin_list_column_content( $column ) {
global $post;
if ( 'billing_info' === $column ) {
$order = wc_get_order( $post->ID );
echo '<p>' . $order->get_billing_last_name() . '</p>';
}
}
add_filter( 'manage_edit-shop_order_sortable_columns', 'my_sortable_name_column' );
function my_sortable_name_column( $columns ) {
$columns['billing_info'] = 'billing_last_name';
return $columns;
}
add_action( 'pre_get_posts', 'name_filter' );
function name_filter( $query ) {
// if it is not admin area, exit the filter immediately
if ( ! is_admin() ) return;
$orderby = $query->get( 'orderby');
if( $orderby == 'billing_info' ) {
$query->set('meta_key', 'billing_last_name' );
$query->set('orderby', 'meta_value');// or meta_value_num
$query->set('order', 'ASC');
}
return $query;
}
The custom column is sortable, so that works but the sort order I want is not applied in a correct way. Someone who can tell me why?