Fix orderby meta handling for `WP_Term_Query`.

In order to allow meta-related values of `orderby` to be handled properly,
the term query's `meta_query` object must run its `get_sql()` method before
`orderby` parsing.

Fixing this bug required addressing another bug in `WP_Meta_Query`, which
caused the table alias index not to be reset when calling `get_sql()`
multiple times on the same object.

Props littler.chicken.
Fixes #37151.

git-svn-id: https://develop.svn.wordpress.org/trunk@37860 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Boone Gorges 2016-06-25 16:22:55 +00:00
parent d4c360d186
commit 255aaa471e
3 changed files with 28 additions and 0 deletions

View File

@ -327,6 +327,8 @@ class WP_Meta_Query {
return false;
}
$this->table_aliases = array();
$this->meta_table = $meta_table;
$this->meta_id_column = sanitize_key( $type . '_id' );

View File

@ -814,6 +814,8 @@ class WP_Term_Query {
protected function parse_orderby_meta( $orderby_raw ) {
$orderby = '';
// Tell the meta query to generate its SQL, so we have access to table aliases.
$this->meta_query->get_sql( 'term', 't', 'term_id' );
$meta_clauses = $this->meta_query->get_clauses();
if ( ! $meta_clauses || ! $orderby_raw ) {
return $orderby;

View File

@ -61,4 +61,28 @@ class Tests_Term_Query extends WP_UnitTestCase {
$this->assertEqualSets( array( $terms[0], $terms[2] ), $q->terms );
}
/**
* @ticket 37151
*/
public function test_order_by_meta_value_num() {
register_taxonomy( 'wptests_tax', 'post' );
$terms = self::factory()->term->create_many( 3, array( 'taxonomy' => 'wptests_tax' ) );
add_term_meta( $terms[0], 'foo', 10 );
add_term_meta( $terms[1], 'foo', 1 );
add_term_meta( $terms[2], 'foo', 100 );
$q = new WP_Term_Query( array(
'taxonomy' => array( 'wptests_tax' ),
'fields' => 'ids',
'hide_empty' => false,
'meta_key' => 'foo',
'orderby' => 'meta_value_num',
) );
$found = array_map( 'intval', $q->terms );
$this->assertSame( array( $terms[1], $terms[0], $terms[2] ), $found );
}
}