Hira Singh
Hira Singh

Reputation: 155

Add meta_type in custom sorting using woocommerce

I am using below code for custom sorting in woocommerce. This is working fine. The only thing is that I have to sort according to numbers. I have used meta_type = UNSIGNED but this is not working.

add_filter( 'woocommerce_get_catalog_ordering_args', 'custom_woocommerce_get_catalog_ordering_args' );

function custom_woocommerce_get_catalog_ordering_args( $args ) {
   $orderby_value = isset( $_GET['orderby'] ) ? woocommerce_clean( $_GET['orderby'] ) :    apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );

 if ( 'timer' == $orderby_value ) {
    $args['meta_key']   = '_auction_dates_to_time';
    $args['meta_type']  = 'UNSIGNED';
    $args['orderby']    = "meta_value";
    $args['order']      = 'ASC';
    $args['paged']      = $paged;
} 
if ( 'timer-desc' == $orderby_value ) {
    $args['meta_key']   = '_auction_dates_to_time';
    $args['meta_type']  = 'UNSIGNED';
    $args['orderby']    = "meta_value";
    $args['order']      = 'DESC';
    $args['paged']      = $paged;
 } 
return $args;
}

add_filter( 'woocommerce_default_catalog_orderby_options', 'custom_woocommerce_catalog_orderby' );
add_filter( 'woocommerce_catalog_orderby', 'custom_woocommerce_catalog_orderby' );

function custom_woocommerce_catalog_orderby( $sortby ) {
   $sortby['timer']   = 'Sort by Bid End Time: low to high';
   $sortby['timer-desc'] = 'Sort by Bid End Time: high to low';
   return $sortby;
}

Please HELP me on this issue.

Thanks

Upvotes: 0

Views: 1419

Answers (1)

Sergiu Paraschiv
Sergiu Paraschiv

Reputation: 10163

Read the docs and the sources again. Regardless of what you set meta_type to in the query (it's actually ignored, there's no such parameter in the docs), the actual data is still stored in the wp_postmeta table, meta_value column that has a LONGTEXT type. Sorting on a LONGTEXT column is supposed to give you those results. That's the way lexicographic order works.

The only thing you can do is CAST that column to a numeric type thus telling the database it should do a numeric sort. You do that with a custom SQL query, or use this built-in WP_Query feature:

orderby (string | array) - Sort retrieved posts by parameter

'meta_value_num' - Order by numeric meta value (available with Version 2.8). Also note that a 'meta_key=keyname' must also be present in the query. This value allows for numerical sorting as noted above in 'meta_value'.

Luckily woocommerce exposes exactly that by setting: $args['orderby'] = "meta_value_num"; because $args is directly sent to WP_Query.

This tells WP_Query to cast meta_value to a numeric type (using +0):

case 'meta_value_num':
    $orderby = "$wpdb->postmeta.meta_value+0";
    break;

Upvotes: 1

Related Questions