How to sort a WP_Query by a custom field AND ALSO filter by a different custom field

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!

Read more here:: How to sort a WP_Query by a custom field AND ALSO filter by a different custom field

Leave a Reply

Your email address will not be published. Required fields are marked *