0

I'm trying to order the products in the frontend by a float attribute (pa_od), I have this code but the order is incorrect

add_action( 'woocommerce_product_query', 'imcar_custom_product_query' );
function imcar_custom_product_query( $query ) {

    if( ! $query->is_main_query() )
        return;

    $query->set( 'orderby', 'pa_od' );
    $query->set( 'order', 'ASC' );

    return $query;
}

The order don't are ASC, The first product have pa_od value 25, the second 12, the third 20.

Thanks

0

OK... First of all, `$query->set( 'orderby', 'pa_od' );' will most probably do nothing. You can't order by some string and think that WordPress will guess what that is.

Here is the list of possible orderby values:

https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters

If you want to order by custom field, then you have to do it this way:

$query->set( 'meta_key', 'pa_od' );
$query->set( 'orderby', 'meta_value' );
$query->set( 'order', 'ASC' );

And because you want to treat that meta value as number, then this is what you really want:

$query->set( 'meta_key', 'pa_od' );
$query->set( 'orderby', 'meta_value_num' );
$query->set( 'order', 'ASC' );

PS. Your function is an action, so you don't need to return anything - the returned value will be ignored anyway... So here's all the code:

add_action( 'woocommerce_product_query', 'imcar_custom_product_query' );
function imcar_custom_product_query( $query ) {

    if( ! $query->is_main_query() )
        return;

    $query->set( 'meta_key', 'pa_od' );
    $query->set( 'orderby', 'meta_value_num' );
    $query->set( 'order', 'ASC' );
}
  • Thanks Krzysiek for the response. With this code any product are listed in the category, this field is one product attribute no custom option. – javiregpa Jul 16 '18 at 17:34
  • WC attributes are stored as taxonomies, AFAIR. If so, then there is no way to sort by them... The only way is to use save_post filter and store that attribute value in custom field and then sort by that CF. – Krzysiek Dróżdż Jul 16 '18 at 17:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.