25% off ProSNIPC25OFF

Exclude Pages/Posts from Search

Removes specific post IDs and/or post types from the front-end search results query.

PHPby SnipCraft
php
<?php
add_action( 'pre_get_posts', 'scseed_exclude_from_search' );
if ( ! function_exists( 'scseed_exclude_from_search' ) ) {
    function scseed_exclude_from_search( $query ) {
        if ( is_admin() || ! $query->is_main_query() || ! $query->is_search() ) {
            return;
        }

        // IDs of individual posts/pages to hide from search results.
        $excluded_ids = apply_filters( 'scseed_search_excluded_ids', [] );
        if ( ! empty( $excluded_ids ) ) {
            $query->set( 'post__not_in', array_map( 'absint', (array) $excluded_ids ) );
        }

        // Post types to remove from search results entirely.
        $excluded_types = apply_filters( 'scseed_search_excluded_post_types', [ 'attachment' ] );
        if ( ! empty( $excluded_types ) ) {
            $public_types = get_post_types( [ 'public' => true, 'exclude_from_search' => false ] );
            $allowed      = array_values( array_diff( $public_types, $excluded_types ) );
            $query->set( 'post_type', $allowed );
        }
    }
}
#content#filtering#frontend#search#ux