Skip to content

Instantly share code, notes, and snippets.

@mcknightd
Created September 26, 2023 19:38
Show Gist options
  • Save mcknightd/ecebb67461ab50b84c2aed20a98c5d53 to your computer and use it in GitHub Desktop.
Save mcknightd/ecebb67461ab50b84c2aed20a98c5d53 to your computer and use it in GitHub Desktop.
Exclude posts from wordpress search that have the yoast setting for 'allow search engines to index' set to 'no'
<?php
// add the below code to your child theme functions file
// exclude yoast noindex pages from wp search
function exclude_noindex_from_search( $query ) {
if(is_admin() || !$query->is_main_query()) {
return;
}
if($query->is_search) {
$meta_query = array(
'relation' => 'OR',
array(
'key' => '_yoast_wpseo_meta-robots-noindex',
'compare' => 'NOT EXISTS',
),
array(
'key' => '_yoast_wpseo_meta-robots-noindex',
'value' => '1',
'compare' => '!=',
),
);
$query->set('meta_query', $meta_query);
}
}
add_filter( 'pre_get_posts', 'exclude_noindex_from_search' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment