0

I have a WP_Query call set to load a custom post type that I've created. I want to be able to alpha-sort by one of the custom fields in the posts (MY_NAME_FIELD in the below code) while ALSO filtering posts that have a specific flag on a different custom field (SHOW_POST in the below code).

Here's what I've tried:

$query_args = array(
  'post_type' => 'MY_POSTTYPE_NAME',
  'post_per_page' => -1,
  'meta_key' => 'SHOW_POST',
  'meta_value' => '1',
  'orderby' => 'MY_NAME_FIELD',
  'order' => 'ASC',
);
$query = new WP_Query( $query_args );

But the above code doesn't seem to work, it's still sorting by entry date. If I remove the orderby and order lines, the filtering part works as expected.

I've found several posts on StackOverflow that show how filtering by multiple custom fields works, but haven't been able to find anything where you're filtering by one custom field and ordering by another, and this is what I need to do.

Thank you in advance for any assistance you can provide!

0

1 Answer 1

1

to sort the posts by a meta field you need to have this field in meta_query and in orderby like this

$query_args = array(
  'post_type' => 'MY_POSTTYPE_NAME',
  'post_per_page' => -1,
  'meta_query' => array( 
      'show_post_query' => array(
          'key' => 'SHOW_POST',
          'value' => '1'
      ),
      'MY_FIELD_NAME__order_by' => array(
          'key' => 'MY_FIELD_NAME',
          'type' => 'NUMERIC',
          'compare' => 'NUMERIC',
      )
  ),
  'orderby' => array( 'MY_FIELD_NAME__order_by' => 'ASC' ),
);
$query = new WP_Query( $query_args );

Note the MY_FIELD_NAME__order_by does not have "value" set so it will not be used for searching but will be (let's say) named so you can use it as column name when sorting.

1
  • Thanks so much! I was able to get it working using this, with a few modifications. Since my MY_FIELD_NAME values are strings, I removed the 'type'=>'NUMERIC' line and changed the compare line to 'EXISTS' and it's working beautifully!
    – da7id
    Commented Jan 31, 2020 at 16:43

Your Answer

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

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