0

I have my query set up like this:

$article_query = new WP_Query(array( 
             'meta_key' => 'issue', 
             'meta_value' => $post->ID , 
             'post_type' => 'article',
             'orderby' => 'order_number', 
             'order' => 'desc'
              ));       

I want all the articles for an issue, sorted by the custom field 'order_number'

As it is, the order is ignored. I have read I need to set meta_key to 'order_number' to enable ordering by that key, but that filters by that key aswel, resulting in no results.

So, how to I sort by order_number?

1

The same problem had been discussed earlier( For reference: Filter by one custom field, order by another? ). Hope this will solve your issue.

1

This is how your code should be:

$args = array(
            'meta_query' => array(
                array(
                    'key' => 'issue',
                    'value' => $post->ID ,
                ),
            ),
            'post_type' => 'article',
            'orderby' => 'meta_value_num',
            'meta_key' => 'order_number',
            'order' => 'DESC'
        );
$article_query = new WP_Query( $args );

Notes:

  1. Meta query must be an array
  2. Sorting by post meta needs orderby to be defined as meta_value (if the values are strings) or meta_value_num (if the values are numbers).
  3. When sorting by post meta, 'meta_key' must follow to determine which meta is the sorting key.
1
  • This also seems to eliminate any posts that don't have 'order_number' as a meta_key.
    – Nathan
    Mar 29 '20 at 17:21

This site is temporarily in read only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .