WordPress.org

Make WordPress Core

Opened 15 months ago

#40341 new enhancement

Make search possible in custom fields

Reported by: max345 Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version: 4.8
Component: Query Keywords:
Focuses: Cc:

Description

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.

Attachments (1)

enhance-search-meta.patch (2.3 KB) - added by max345 15 months ago.
add search_meta parameter in WP_Query to enable search in listed custom fields

Download all attachments as: .zip

Change History (1)

@max345
15 months ago

add search_meta parameter in WP_Query to enable search in listed custom fields

Note: See TracTickets for help on using tickets.