0

How do I exclude a specific page (and child pages) from the search results?

I've seen posts showing how to exclude all pages. I don't want that. I want to target a page and it's children and exclude them and only them.

1
// Filter to exclude a page and it's child pages from search query
function myfilter_exclude_pages_from_search( $query ) {

    // Save the post id of the page to be excluded in $parent_post_id_to_exclude
    $parent_post_id_to_exclude = 111; // Replace 111 with actual page id
    // Convert the post id to an array
    $parent_post_id_arr = array( $parent_post_id_to_exclude ); 

    // Apply filter only if this is a search query and not on admin panel
    if ( $query->is_search && !is_admin() ) {

        // Search only for pages
        $query->set( 'post_type', 'page');

        // Exclude the page id
        $query->set( 'post__not_in', $parent_post_id_arr );

        // Exclude all child pages of selected page id
        $query->set( 'post_parent__not_in', $parent_post_id_arr );
    }
    return $query;
}
add_filter( 'pre_get_posts', 'myfilter_exclude_pages_from_search' );

Read below article for other use cases for pre_get_posts
https://www.wpbeginner.com/plugins/how-to-exclude-specific-pages-authors-and-more-from-wordpress-search/

Reference for parameters to WP_Query : https://developer.wordpress.org/reference/classes/wp_query/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.