From 255aaa471e6a3c2090ff44eb65cf31ce860a76d5 Mon Sep 17 00:00:00 2001 From: Boone Gorges Date: Sat, 25 Jun 2016 16:22:55 +0000 Subject: [PATCH] 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 --- src/wp-includes/class-wp-meta-query.php | 2 ++ src/wp-includes/class-wp-term-query.php | 2 ++ tests/phpunit/tests/term/query.php | 24 ++++++++++++++++++++++++ 3 files changed, 28 insertions(+) diff --git a/src/wp-includes/class-wp-meta-query.php b/src/wp-includes/class-wp-meta-query.php index affb83af64..4019912019 100644 --- a/src/wp-includes/class-wp-meta-query.php +++ b/src/wp-includes/class-wp-meta-query.php @@ -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' ); diff --git a/src/wp-includes/class-wp-term-query.php b/src/wp-includes/class-wp-term-query.php index 924a1e8c4d..dd42166cfd 100644 --- a/src/wp-includes/class-wp-term-query.php +++ b/src/wp-includes/class-wp-term-query.php @@ -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; diff --git a/tests/phpunit/tests/term/query.php b/tests/phpunit/tests/term/query.php index d1f875bcaa..37dbe48f23 100644 --- a/tests/phpunit/tests/term/query.php +++ b/tests/phpunit/tests/term/query.php @@ -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 ); + } }