Site logo

Archived topic

Exclude pages from search

9 replies · Started by Nicole on January 20, 2023

Viewing posts 1–10 of 10

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!

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.

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

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/

Thank you so much!

Glad to be of help!

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

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.

Thanks very much!

You're welcome

This archived topic is closed to new replies.