Exclude or Include by custom field values
Last updated
Last updated
There are two ways of excluding results by custom field values, either by using a hidden filter or using a custom code.
Using a hidden custom field filter is a great option, as it does not require any custom coding, and it will work even if you don't have the front-end options enabled.
Go to the Frontned search settings -> Custom fields panel
Go ahead and create a new filter as shown on the picture below
Save the options.
Example: Excluding results, where field 'my_field' does not equal to 1
The filter will be active, even if the front-end search settings are disabled.
In some cases, you might want to still show results that does not have the custom field assigned, that you defined in the filter.
For that, just make sure to turn on the Allow results with missing custom fields, when using custom field selectors option on the Frontned search settings -> Advanced panel:
By making changes to the search query arguments right before the search process, it is possible to append additional results filters (including custom field fitlers) to it.
The post meta filter argument array looks like this:
Example filter code: Excluding results, where field 'my_field' does not equal to 1
Use this custom code as a sample in the functions.php in your theme/child theme directory. Before editing, please make sure to have a full site back-up just in case!