Exclude or Include by custom field values

There are two ways of excluding results by custom field values, either by using a hidden filter or using a custom code.

1. Excluding/Including by creating a hidden filter

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.

  1. Go to the Frontned search settings -> Custom fields panel

  2. Go ahead and create a new filter as shown on the picture below

  3. 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.

1.1 Including results that does not have the custom field defined

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:

2. Excluding/Including by using a custom code

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:

$args['post_meta_filter'] = array(
    array(
        'key'     => 'age',         // meta key
        'value'   => array( 3, 4 ), // mixed|array
         // @param string|array compare
         // Numeric Operators
         //      '<' -> less than
         //      '>' -> more than
         //      '<>' -> not equals
         //      '=' -> equals
         //      'BETWEEN' -> between two values
         // String Operators
         //      'LIKE'
         //      'NOT LIKE'
         //
        'operator' => 'BETWEEN',
        'allow_missing' => true    // allow match if this custom field is unset
    )
    // .. additional rules ..
);

Example filter code: Excluding results, where field 'my_field' does not equal to 1

add_filter('asp_query_args', 'asp_add_my_meta_filter', 10, 1);
function asp_add_my_meta_filter( $args ) {
  $args['post_meta_filter'][] = array(
    'key' => 'my_field',
    'value' => 1,
    'operator' => '<>',
    'allow_missing' => true
  );
  return $args;
}

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!

Last updated

Copyright Ernest Marcinko