[wp-trac] [WordPress Trac] #40630: Advanced meta compare "like" in WP_Query

WordPress Trac noreply at wordpress.org
Tue May 16 15:17:41 UTC 2017


#40630: Advanced meta compare "like" in WP_Query
------------------------------+------------------------------
 Reporter:  sebastian.pisula  |       Owner:
     Type:  defect (bug)      |      Status:  new
 Priority:  normal            |   Milestone:  Awaiting Review
Component:  Query             |     Version:  4.7.4
 Severity:  normal            |  Resolution:
 Keywords:  has-patch         |     Focuses:
------------------------------+------------------------------
Changes (by subrataemfluence):

 * keywords:   => has-patch
 * version:   => 4.7.4


Comment:

 WordPress automatically adds leading and trailing % to the text (value)
 passed via LIKE operator and escapes special characters ({{{_, % and back
 slash (\)}}}) if found inside the value passed.

 In `wp-includes\wp-db.php` the following snippet does this automatically
 for us:

 {{{#!php
 <?php
 public function esc_like( $text ) {
    return addcslashes( $text, '_%\\' );
 }
 }}}


 In your example, the value (`i%st`) you passed has a % sign in it hence
 WordPress automatically escapes it by invoking the above function with and
 converts it to `%i\\%st%`. Look how WordPress has automatically added one
 leading and one trailing % sings to your actual value.

 My patch will prevent WordPress from escaping % sign inside a value (like
 yours) and will output your query to

 {{{
 SELECT SQL_CALC_FOUND_ROWS  wp_posts.ID FROM wp_posts  INNER JOIN
 wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) WHERE 1=1  AND (
   ( wp_postmeta.meta_key = '_stock_status' AND wp_postmeta.meta_value LIKE
 '%i%st%' )
 ) AND wp_posts.post_type IN ('post', 'page', 'attachment', 'product') AND
 (wp_posts.post_status = 'publish') GROUP BY wp_posts.ID ORDER BY
 wp_posts.post_date DESC LIMIT 0, 10
 }}}

 Now it should return your desired result.

--
Ticket URL: <https://core.trac.wordpress.org/ticket/40630#comment:1>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list