[wp-trac] [WordPress Trac] #40341: Make search possible in custom fields

WordPress Trac noreply at wordpress.org
Sun Apr 2 17:36:07 UTC 2017


#40341: Make search possible in custom fields
-------------------------+-----------------------------
 Reporter:  max345       |      Owner:
     Type:  enhancement  |     Status:  new
 Priority:  normal       |  Milestone:  Awaiting Review
Component:  Query        |    Version:  trunk
 Severity:  normal       |   Keywords:
  Focuses:               |
-------------------------+-----------------------------
 Currently when performing a search query with `WP_Query` using `s`
 parameter, WordPress only searches in post_title, post_content and
 post_excerpt. I suggest to extend search to custom fields.

 Say I added a "my_description" custom post field to my posts. I would like
 a regular search to return every post containing the searched word(s) in
 any of the fields post_title, post_content, post_excerpt or
 my_description.

 Currently the supposed way of doing this is by using a `WP_Meta_Query`:

 {{{
 new WP_Query(array(
   's' => 'foo',
   'meta_query' => array(array(
     'key'     => 'my_description',
     'value'   => 'foo',
     'compare' => 'LIKE',
   )),
 ))
 }}}

 The problem is that the meta query and the search WHERE clauses are going
 to be joined by AND, not by OR. The resulting query is going to be
 something like that:

 {{{
 SELECT [...] WHERE
 (
   posts.post_title LIKE '%foo%'
   OR posts.post_content LIKE '%foo%'
   OR posts.post_excerpt LIKE '%foo%'
 ) AND (
   postmeta.meta_key = 'my_description' AND postmeta.meta_value LIKE
 '%foo%'
 ) AND [...]
 }}}

 But I'd need:

 {{{
 SELECT [...] WHERE
 (
   posts.post_title LIKE '%foo%'
   OR posts.post_content LIKE '%foo%'
   OR posts.post_excerpt LIKE '%foo%'
   OR (postmeta.meta_key = 'my_description' AND postmeta.meta_value LIKE
 '%foo%')
 ) AND [...]
 }}}

 which is impossible to achieve with a regular `WP_Meta_Query`. Actually
 it's pretty hard to do: it involves to hook into WHERE and JOIN clauses,
 and to rewrite almost the whole search mechanism.

 That's why I suggest to implement into core a simple way of doing this:

 {{{
 new WP_Query(array(
   's' => 'foo',
   'meta_search' => array('my_description', 'my_other_field', 'etc')
 ))
 }}}

 This `meta_search` parameter would accept an array of meta_key strings and
 would just be ignored when not set.

 Please have a look into my attached solution.

--
Ticket URL: <https://core.trac.wordpress.org/ticket/40341>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list