Skip to content

Instantly share code, notes, and snippets.

@phlbnks
Created January 31, 2018 15:58
Show Gist options
  • Save phlbnks/ea5de7340cffc1bf1aa5c4cec00de096 to your computer and use it in GitHub Desktop.
Save phlbnks/ea5de7340cffc1bf1aa5c4cec00de096 to your computer and use it in GitHub Desktop.
Exclude posts with a custom meta value from search
<?php
/**
* Exclude posts with 'fruit' custom meta field value of 'bananas' from site Search
*/
function cc_search_filter( $query ) {
if ( ! is_admin() && $query->is_main_query() ) {
if ( $query->is_search ) {
$query->set( 'meta_query',
array(
'relation' => 'OR',
array(
'key' => 'fruit',
'value' => 'Banana',
'compare' => '!=',
),
array(
'key' => 'fruit',
'compare' => 'NOT EXISTS',
),
)
);
}
}
}
add_action( 'pre_get_posts', 'cc_search_filter' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment