Make WordPress Core

Opened 3 years ago

Closed 3 years ago

Last modified 3 years ago

#16814 closed defect (bug) (duplicate)

WP_Query doesn't check orderby for meta_query

Reported by: dalesaurus Owned by:
Milestone: Priority: normal
Severity: normal Version: 3.1
Component: Query Keywords:
Focuses: Cc:


With the new join style in 3.1 for Custom Post Types, an array must be set on WP_Query with meta_query. In query.php line 2274 all cases of orderby are processed, specifically creating an array called $allowed_keys.

This check looks only for the deprecated meta_key. This will cause any sorting on a Custom Post Type meta_value to fail.

// Fix proposal (until meta_key goes away)
if ( !empty($q['meta_query']) || !empty($q['meta_key']) ) {
    $allowed_keys[] = $q['meta_key'];
    $allowed_keys[] = 'meta_value';
    $allowed_keys[] = 'meta_value_num';

Temporary workaround for people with broken sorts is to set meta_key in addition to setting the meta_query variable.

// Example 1
set_query_var( 'meta_query', array( array( 'key' => 'my_key_name',  'compare' => '>','value' => '1','type' => 'NUMERIC' ) ) );
set_query_var( 'orderby','meta_value' );
set_query_var( 'meta_key', 'my_key_name' ); // need this

// Example 2
$wpq->set( 'meta_query', array( 
                'key' => 'my_key_name',
                'compare' => '>',
                'value' => '1',
                'type' => 'NUMERIC'
$wpq->set( 'orderby','meta_value' );
$wpq->set( 'meta_key', 'my_key_name' ); // need this

Change History (5)

comment:1 hakre3 years ago

in your example in the description: $wpq ?

comment:2 scribu3 years ago

Related: #16812

comment:3 dalesaurus3 years ago

$wpq can be any WP_Query object.

comment:4 scribu3 years ago

  • Milestone Awaiting Review deleted
  • Resolution set to duplicate
  • Status changed from new to closed
  • Summary changed from WP_Query doesn't check orderby for Custom Post Types querying with meta_query to WP_Query doesn't check orderby for meta_query

First of all, this has nothing to do with custom post types. It affects regular posts as well.

I'm closing this ticket as a duplicate of #15031, since it's basically the same problem.

Feel free to join the discussion there.

comment:5 scribu3 years ago

Also note that 'meta_key', 'meta_value' and 'meta_compare' aren't deprecated.

Last edited 3 years ago by scribu (previous) (diff)
Note: See TracTickets for help on using tickets.