Halloween Sale 15% off Ends in See the plans
PHP

Leave Noindexed Content Out of Site Search

Hides posts and pages that you set to noindex in Yoast SEO or Rank Math from your own site search, such as thank-you pages and thin landing pages.

Don’t have WPIDE yet? Install it on your site

Code

add_filter( 'posts_where', function ( $where, $query ) {
    global $wpdb;

    if ( is_admin() || ! $query->is_main_query() || ! $query->is_search() ) {
        return $where;
    }

    // Yoast SEO: "Allow search engines to show this content" set to No.
    if ( defined( 'WPSEO_VERSION' ) ) {
        $where .= " AND NOT EXISTS ( SELECT 1 FROM {$wpdb->postmeta} wpide_ny WHERE wpide_ny.post_id = {$wpdb->posts}.ID AND wpide_ny.meta_key = '_yoast_wpseo_meta-robots-noindex' AND wpide_ny.meta_value = '1' )";
    }

    // Rank Math: "No Index" ticked in the robots meta.
    if ( defined( 'RANK_MATH_VERSION' ) ) {
        $where .= " AND NOT EXISTS ( SELECT 1 FROM {$wpdb->postmeta} wpide_nr WHERE wpide_nr.post_id = {$wpdb->posts}.ID AND wpide_nr.meta_key = 'rank_math_robots' AND wpide_nr.meta_value LIKE '%noindex%' )";
    }

    return $where;
}, 10, 2 );

Notes

Uses each post's own robots setting; content type-wide noindex settings in the SEO plugin are not checked.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.