Site logo

[Resolved] Exclude pages from search

Home Forums Support [Resolved] Exclude pages from search

Home Forums Support Exclude pages from search

Viewing 10 posts - 1 through 10 (of 10 total)
  • Author
    Posts
  • #2502696
    Nicole

    Is there a way to exclude specific pages from the internal search?

    Ideally, I would like to exclude the pages that are set to no index if possible.
    If not, then I would like to exclude specific pages by URL.

    Thanks in advance!

    #2502753
    David
    Staff
    Customer Support

    Hi there,

    you can exclude pages with this snippet and adding their IDs in the array

    `add_filter( ‘pre_get_posts’, ‘db_exclude_pages_in_search’ );
    function db_exclude_pages_in_search($query) {
    if ( $query->is_search )
    $query->set( ‘post__not_in’, array( 1, 2, 3, 4, 5 ) );

    return $query;
    }

    How are the pages being set to noindex ? it might be possible to get their ids so you don’t have to.

    #2502768
    Nicole

    Thanks so much for the quick reply. They are being no indexed via Yoasts SEO plugin.

    #2502797
    David
    Staff
    Customer Support

    Try this function:

    function be_exclude_noindex_from_search( $query ) {
    
    	if( $query->is_main_query() && $query->is_search() && ! is_admin() ) {
    
    		$meta_query = isset( $query->meta_query ) ? $query->meta_query : array();
    		$meta_query['noindex'] = array(
    			'key' => '_yoast_wpseo_meta-robots-noindex',
    			'value' => 1,
    			'compare' => 'NOT EXISTS',
    		);
    
    		$query->set( 'meta_query', $meta_query );
    	}
    }
    add_action( 'pre_get_posts', 'be_exclude_noindex_from_search' );

    For reference and kudos, it came from this site:

    https://www.billerickson.net/code/exclude-no-index-content-from-wordpress-search/

    #2502856
    Nicole

    Thank you so much!

    #2502859
    David
    Staff
    Customer Support

    Glad to be of help!

    #2502864
    Nicole

    Sorry, one last question. Is this a snippet or a hook? I’m not sure where to put the code…

    #2502896
    David
    Staff
    Customer Support

    Its a PHP Snippet.
    This doc explains how to add the code:
    https://docs.generatepress.com/article/adding-php/

    TLDR: Are you using a Child Theme?
    If Yes, then you can add the code to your Child Themes functions.php
    If No, then use the Code Snippets plugin ( link in the above doc ) and Add New Snippet for the code.

    #2503110
    Nicole

    Thanks very much!

    #2503313
    David
    Staff
    Customer Support

    You’re welcome

Viewing 10 posts - 1 through 10 (of 10 total)
  • You must be logged in to reply to this topic.