0

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.

3
  • I'm not sure if the orderby key accepts an array. It's a string value. Commented Jul 24 at 4:50
  • Right now your query will filter out posts having a particular height and a width. I'm not sure what you mean by "first by height and then by width". In order to filter posts based on height, you'll need to remove clause2 item from $meta_query. To filter posts based on width, it will be a different query in which you'll have to remove clause1 item from $meta_query. Commented Jul 29 at 2:07

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.