Created
June 11, 2020 11:52
-
-
Save blogjunkie/dae02fa5eb2484e704a75c555c4cdc0d to your computer and use it in GitHub Desktop.
Exclude pages that have been noindex-ed in Yoast SEO from WP search
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php // Do not copy this line | |
| add_filter( 'pre_get_posts', 'dw_exclude_noindex_content_from_search' ); | |
| function dw_exclude_noindex_content_from_search($query) { | |
| // Only run this query for searches when not inside the admin | |
| if ( $query->is_search && !is_admin() ) { | |
| // Find all posts with `_yoast_wpseo_meta-robots-noindex` postmeta that equal to `1` | |
| $args = array( | |
| 'post_type' => 'any', | |
| 'posts_per_page'=> -1, | |
| 'post_status' => 'publish', | |
| 'meta_query' => array( | |
| array( | |
| 'key' => '_yoast_wpseo_meta-robots-noindex', | |
| 'value' => '1', | |
| ), | |
| ) | |
| ); | |
| $exclude_query = new WP_Query( $args ); | |
| // Create array of post IDs only | |
| $exclude_posts_array = array(); | |
| // Fill the array | |
| if ( $exclude_query->have_posts() ) { | |
| while ( $exclude_query->have_posts() ) { | |
| $exclude_query->the_post(); | |
| $exclude_posts_array[] = get_the_id(); | |
| } | |
| } | |
| // Reset the query | |
| wp_reset_postdata(); | |
| // Modify the search query to exclude the noindex-ed content | |
| $query->set( 'post__not_in', $exclude_posts_array ); | |
| } | |
| return $query; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment