From 41db99c31a0dd6bbd1e98de00b64c3733149030c Mon Sep 17 00:00:00 2001 From: Boone Gorges Date: Fri, 6 Feb 2015 02:01:24 +0000 Subject: [PATCH] Use field-specific sanitization in `WP_Tax_Query::transform_query()`. When terms are entered into the database, term fields are sanitized with `sanitize_term_field()`. To ensure that the `SELECT ... WHERE` queries in `WP_Tax_Query::transform_query()` are not broken by overzealous sanitization, `sanitize_term_field()` should be used in that case as well. This fixes a bug where a tax_query using 'field=name' would fail if the 'terms' parameter contained characters (like spaces) that were improperly removed by `sanitize_title_for_query()`. Fixes #27810. git-svn-id: https://develop.svn.wordpress.org/trunk@31346 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/taxonomy.php | 12 ++++++++++- tests/phpunit/tests/query/taxQuery.php | 30 ++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/src/wp-includes/taxonomy.php b/src/wp-includes/taxonomy.php index ec398b44aa..6deb0030d4 100644 --- a/src/wp-includes/taxonomy.php +++ b/src/wp-includes/taxonomy.php @@ -1226,7 +1226,17 @@ class WP_Tax_Query { switch ( $query['field'] ) { case 'slug': case 'name': - $terms = "'" . implode( "','", array_map( 'sanitize_title_for_query', $query['terms'] ) ) . "'"; + foreach ( $query['terms'] as &$term ) { + /* + * 0 is the $term_id parameter. We don't have a term ID yet, but it doesn't + * matter because `sanitize_term_field()` ignores the $term_id param when the + * context is 'db'. + */ + $term = "'" . sanitize_term_field( $query['field'], $term, 0, $query['taxonomy'], 'db' ) . "'"; + } + + $terms = implode( ",", $query['terms'] ); + $terms = $wpdb->get_col( " SELECT $wpdb->term_taxonomy.$resulting_field FROM $wpdb->term_taxonomy diff --git a/tests/phpunit/tests/query/taxQuery.php b/tests/phpunit/tests/query/taxQuery.php index eed12ac371..a9b7cf71f8 100644 --- a/tests/phpunit/tests/query/taxQuery.php +++ b/tests/phpunit/tests/query/taxQuery.php @@ -59,6 +59,36 @@ class Tests_Query_TaxQuery extends WP_UnitTestCase { $this->assertEquals( array( $p1 ), $q->posts ); } + /** + * @ticket 27810 + */ + public function test_field_name_should_work_for_names_with_spaces() { + register_taxonomy( 'wptests_tax', 'post' ); + + $t = $this->factory->term->create( array( + 'taxonomy' => 'wptests_tax', + 'slug' => 'foo', + 'name' => 'Foo Bar', + ) ); + $p1 = $this->factory->post->create(); + $p2 = $this->factory->post->create(); + + wp_set_object_terms( $p1, $t, 'wptests_tax' ); + + $q = new WP_Query( array( + 'fields' => 'ids', + 'tax_query' => array( + array( + 'taxonomy' => 'wptests_tax', + 'terms' => array( 'Foo Bar' ), + 'field' => 'name', + ), + ), + ) ); + + $this->assertEquals( array( $p1 ), $q->posts ); + } + public function test_tax_query_single_query_single_term_field_term_taxonomy_id() { $t = $this->factory->term->create( array( 'taxonomy' => 'category',