Support

Account

Home Forums General Issues Query Posts by One Custom Field and 'orderby' Another Custom Field

Solved

Query Posts by One Custom Field and 'orderby' Another Custom Field

  • I’m trying to write a query that selects posts by a certain custom field, and then sets the ‘orderby’ parameter to the value of another custom field. How would I write this?

    I’ve tried to combine the ideas from the ‘Query by custom field’ and ‘Order by custom field’ support docs to no avail. Do I have to write a meta_query, even though I am only selecting my posts by one field value? How do I incorporate the ‘orderby’ value into the query?

  • This reply has been marked as private.
  • Yes, you will need to add a meta_query to do this.

    There was a new feature added in WP4.2 that would allow you to do this.

    And you’ll need to query by the field you are ordering by as well. See the city_clause example.

    https://make.wordpress.org/core/2015/03/30/query-improvements-in-wp-4-2-orderby-and-meta_query/

  • Thanks, John. That document was helpful.

    For someone else who may stumble across this article and find my query helpful, here it is:

    	$my_query = new WP_Query(array(
            'category_name' => 'artist',
            'posts_per_page' => -1,
            'meta_query' => array(
                'relation' => 'AND',
                'gender_clause' => array(
                    'key' => 'gender',
                    'value' => 'f',
                ),
                'sort_clause' => array(
                    'key' => 'sort_name',
                    'compare' => 'EXISTS',
                ),
            ),
            'orderby' => 'sort_clause',
            'order' => 'ASC',
        ));

    Basically, I am querying posts of the ‘artist’ category, and then selecting those posts where the ‘gender’ (a custom field I have setup) is set to the value of ‘f’. There is another custom field called ‘sort_name’ that I use to order the posts by.

Viewing 4 posts - 1 through 4 (of 4 total)

The topic ‘Query Posts by One Custom Field and 'orderby' Another Custom Field’ is closed to new replies.