diff --git a/src/wp-includes/class-wp-term-query.php b/src/wp-includes/class-wp-term-query.php index cfb4474d05..2d3d085af3 100644 --- a/src/wp-includes/class-wp-term-query.php +++ b/src/wp-includes/class-wp-term-query.php @@ -384,6 +384,10 @@ class WP_Term_Query { } $orderby = $this->parse_orderby( $this->query_vars['orderby'] ); + if ( $orderby ) { + $orderby = "ORDER BY $orderby"; + } + $order = $this->parse_order( $this->query_vars['order'] ); if ( $taxonomies ) { @@ -618,7 +622,7 @@ class WP_Term_Query { $this->sql_clauses['select'] = "SELECT $distinct $fields"; $this->sql_clauses['from'] = "FROM $wpdb->terms AS t $join"; - $this->sql_clauses['orderby'] = $orderby ? "ORDER BY $orderby $order" : ''; + $this->sql_clauses['orderby'] = $orderby ? "$orderby $order" : ''; $this->sql_clauses['limits'] = $limits; $this->request = "{$this->sql_clauses['select']} {$this->sql_clauses['from']} {$where} {$this->sql_clauses['orderby']} {$this->sql_clauses['limits']}"; diff --git a/tests/phpunit/tests/term/query.php b/tests/phpunit/tests/term/query.php index 37dbe48f23..9a5a29583f 100644 --- a/tests/phpunit/tests/term/query.php +++ b/tests/phpunit/tests/term/query.php @@ -85,4 +85,26 @@ class Tests_Term_Query extends WP_UnitTestCase { $found = array_map( 'intval', $q->terms ); $this->assertSame( array( $terms[1], $terms[0], $terms[2] ), $found ); } + + /** + * @ticket 37378 + */ + public function test_order_by_keyword_should_not_be_duplicated_when_filtered() { + register_taxonomy( 'wptests_tax', 'post' ); + + add_filter( 'terms_clauses', array( $this, 'filter_terms_clauses' ) ); + $q = new WP_Term_Query( array( + 'taxonomy' => array( 'wptests_tax' ), + 'orderby' => 'name', + ) ); + remove_filter( 'terms_clauses', array( $this, 'filter_terms_clauses' ) ); + + $this->assertContains( 'ORDER BY tt.term_id', $q->request ); + $this->assertNotContains( 'ORDER BY ORDER BY', $q->request ); + } + + public function filter_terms_clauses( $clauses ) { + $clauses['orderby'] = 'ORDER BY tt.term_id'; + return $clauses; + } }