Support » Developing with WordPress » Creating a search function for meta data and content

Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator bcworkz

    (@bcworkz)

    You’re very close with what you have. Omit the ‘key’ array element in the meta query. Then WP will find the search value in postmeta.meta_value column regardless of key value. Do not include the SQL wildcard char % in your search term, WP will assume you want them and add them itself.

    If you must only find a meta value in several keys but not any key, you can supply an array of key values that are to be searched as the ‘key’ arg.

    Also add a ‘s’ array element to the main array with your search term so the query will also look for the term in title, excerpt, or content. WP assumes you want AND logic applied between the ‘s’ and ‘meta_query’ args, that there needs to be a match in both args. But OR logic is applied within the various ‘s’ fields searched. The ‘s’ search term and ‘meta_query’ search terms don’t have to be the same, but could be.

    WP_Query does not have an option to specify OR logic between ‘s’ and ‘meta_query’. If you need such logic, use the “posts_request” filter to directly alter the SQL. Use PHP string search and replace methods to find the right “AND” and replace it with “OR”.

    Thread Starter nikon001

    (@nikon001)

    Thank you.

    The problem I see right now is that when I do add the ‘s’ at the top there that receives $search_query, then nothing happends.
    Only when I removed the ‘s’, I did get a search result, but then only for meta data.

    You talking about relation. To I have to add ‘relation’ => ‘OR’ after ‘meta_query’ => array, before the second array ?

    Instead of re-inventing the wheel, this plugin searches title, content, and meta. You can select what you want it to search:

    https://en-ca.wordpress.org/plugins/wp-extended-search/

    You can also look at the source code if you want to copy the implementation.

    There’s also these instructions https://adambalee.com/search-wordpress-by-custom-fields-without-a-plugin/ if you don’t want to use a plugin.

    Moderator bcworkz

    (@bcworkz)

    Lukasz’ plugin suggestion sounds promising, but to answer your question, when there’s only one inner array for “meta_query”, there’s no reason to provide any meta query relation arg since there’s only one meta query arg — there’s nothing to OR against.

    Sounds like you want OR logic between the ‘s’ criteria and meta query criteria? That’s not possible with WP_Query args alone, you need to adjust the SQL through the “posts_request” filter. Or use the plugin Lukasz suggested.

    A 3rd option is to compose your own SQL query and run it with methods of the global $wpdb connection object.

Viewing 4 replies - 1 through 4 (of 4 total)
  • You must be logged in to reply to this topic.