Skip to content

Instantly share code, notes, and snippets.

@kevinlisota
Last active February 5, 2021 20:35
Show Gist options
  • Save kevinlisota/6680444b0c10fef9b992 to your computer and use it in GitHub Desktop.
Save kevinlisota/6680444b0c10fef9b992 to your computer and use it in GitHub Desktop.
Excluding certain posts from WordPress search results based on custom field values
function exclude_nonadvertorial_search($query) {
//only run for the main query and don't run on admin pages
if (!is_admin() && $query->is_main_query()) {
//now check to see if you are on a search results page
if ($query->is_search) {
//get sponsor posts that are NOT advertorials, so we can exclude their IDs from search
$args = array(
//get posts of the custom post type sponsor_post
'post_type' => 'sponsor_post',
//get all posts
'posts_per_page' => -1,
//return an array of post IDs
'fields' => 'ids',
//now check for posts that have a sponsor_post_type that is not 'advertorial'
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'sponsor_post_type',
'value' => 'advertorial',
'compare' => '!='
),
//some posts don't have a sponsor_post_type meta field set, so check for those too
array(
'key' => 'sponsor_post_type',
'compare' => 'NOT EXISTS'
)
)
);
//now get the posts
$excluded_ids = get_posts($args);
//add these post IDs to the 'post__not_in' query parameter
$query->set('post__not_in', $excluded_ids);
}
}
}
add_action('pre_get_posts', 'exclude_nonadvertorial_search');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment