Skip Navigation

[Resolved] Exclude custom posts from search results, but allow archives

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
- 10:00 – 13:00 10:00 – 13:00 10:00 – 13:00 10:00 – 13:00 10:00 – 13:00 -
- 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 -

Supporter timezone: Asia/Kolkata (GMT+05:30)

This topic contains 1 reply, has 1 voice.

Last updated by katjaL 2 hours, 21 minutes ago.

Assisted by: Minesh.

Author
Posts
#2797898

Hi,
I need to hide the custom posts from WP default search and when I activate the "exclude_from_search" this works ok. But we need to use archives of custom taxonomies and they don't work if "exclude_from_search" is activated. They do work fine if it's not activated.

Is this normal and can I make the archives work for this post type even though the posts are not included in search results?

#2797908

Minesh
Supporter

Languages: English (English )

Timezone: Asia/Kolkata (GMT+05:30)

Hello. Thank you for contacting the Toolset support.

Basically - you can use the standard WordPress hook "pre_get_posts" in order to make sure what post types you want to include.

For instance:

function func_default_search_filter( $query ) {
    // If the query is_admin() bail
    if ( $query->is_admin() ) :
        return $query;
    endif;
    
    // If the query is_search and is_main_query
    if ( $query->is_search() && $query->is_main_query() ) {
        // set the post type to only post types you want returned.
        $include_post_types = array('page', 'post');
        $query->set( 'post_type',$include_post_types  );
    }
    
    // Return the query.
    return $query;
}
add_action( 'pre_get_posts', 'func_default_search_filter' );

Where:
- You can adjust the array values for $include_post_types variable for post types you want to include for the searcch.

You can add the above code to your current theme's functions.php file or "Custom Code" section offered by Toolset.
- https://toolset.com/documentation/programmer-reference/adding-custom-code/using-toolset-to-add-custom-code/

#2797915

Yes! Thank you Minesh!