I have a site using Advanced Custom Fields to create and store various bits of relevant info. These need to be included in the main general search, which by default only searches the title and main content.
I’ve found plenty of info about getting search results based on specific bits of postmeta, but I have an issue with that. There are a potentially unlimited amount of potential fields in postmeta to search.
The solution could either search anything in postmeta or anything with a meta_key that matches this regex: content_section_[0-9]{1,4}_content_.{2,8}
Example meta_keys to match are:
content_section_0_content_title
content_section_0_content_title
content_section_4_content_subtitle
content_section_8_content_text
Any way that I can alter the fields searched to include the postmeta would be very much appreciated.
If your up for using a plugin, Relevanssi – A Better Search might be worth trying out.
The standard (free) version supports searching post meta.
Add this to your plugin or functions.php file of your theme. The example below will include ‘your_key’ in search. You can include all your keys by repeating the array.
This function should work, even after WP 4.8.3 security update.
Usage:
Implementation:
Several people have done this in different ways:
http://websmartdesign.nz/searching-structured-post-data-with-wordpress/
https://adambalee.com/search-wordpress-by-custom-fields-without-a-plugin/
This is an improved Ahmed’s answer:
The problem is that WordPress generates meta query with “AND” operator, and it would show only posts which have search string in both places – title AND meta, or content AND meta. So, we need to create an additional filter to change “AND” to “OR” (and then remove that filter to not break anything else).
This is the most simple and currently working solution. None of the above worked for me. It is tested and working with WordPress 5.3.1 .
Place the following code in your functions.php file to hook into
posts_clauses
filter.And your query should look like the following. Please note that
suppress_filters => false
is mandatory! It will not work without it.I’m not sure, but to grab all the custom field keys/values for the default search would require a database call using wpdb.
The alternative plugin besides the ones goto10 mentioned are a much simpler solution.
Search Everything, WP Custom Fields Search