I'm working with lumber and have custom post types with ACF fields for height and width in decimals.
I'm trying to sort my posts first by height and then by width. I am using the following code:
// sort stock and custom profiles by height first then width
add_action( 'pre_get_posts', function ( $query ) {
if( is_admin() ) {
return $query;
}
// Check if post_type is either 'stock' or 'custom'
if( isset($query->query_vars['post_type']) && ($query->query_vars['post_type'] == 'stock' || $query->query_vars['post_type'] == 'custom') ) {
$meta_query = array(
'relation' => 'AND',
'clause1' => array(
'key' => 'height_decimal',
'compare' => 'EXISTS',
),
'clause2' => array(
'key' => 'width_decimal',
'compare' => 'EXISTS',
)
);
$query->set('meta_query', $meta_query);
$query->set('orderby', array(
'clause1' => 'ASC',
'clause2' => 'ASC'
));
}
// Return the modified query
return $query;
} );
This is working great in post archive and taxonomy archive pages. But I have a filter on the categories and when the filter is used they stay in order BUT it switches to a lexicographic order instead of numeric.
So on the taxonomy archive page the order is:
0.1 0.200 0.3 0.4
But when the Ajax filter is applied the order switches to:
0.1 0.3 0.4 0.200
I have tried adding
'type' => 'NUMERIC',
to my two clauses but that removes the custom sorting all together.
orderby
key accepts an array. It's a string value.clause2
item from$meta_query
. To filter posts based on width, it will be a different query in which you'll have to removeclause1
item from$meta_query
.