I am trying to use the pre_get_posts
action hook to sort products by ACF field for archive product pages.
The ACF field is a string, that contains characters and numeric value
My solution: to add missing leading zero’s so that ‘040’ < ‘180’ will hold.
The following code is NOT working. What am I missing?
function sort_batteries_by_amper( $query ) {
if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'product' ) {
$query->set('orderby', 'meta_value');
$query->set('meta_key', 'MY_KEY');
$query->set('order', 'ASC');
$value = get_ah_value($query, 'MY_KEY'); // add leading zero's to int values < 100
$query->set( 'meta_value', $value );
}
return $query;
}
add_action('pre_get_posts', 'sort_batteries_by_amper');
2
Answers
The following is a complete solution that works
Try
in place of