Site Overlay

Obi Remove Post Types from Search

This idea started from a pain point customers used to have at LearnDash. Sometimes, they would request a way to exclude some of the LearnDash post types, such as Lessons and Topics, from the WordPress search feature.

A solution for this is using the following snippet:

/**
 * Exclude Post Type from Search
 */
add_action('init', 'obi_exclude_cpt_from_wp_search', 99);

function obi_exclude_cpt_from_wp_search(){
    global $wp_post_types;

    if(post_type_exists('your_cpt_name') && isset($wp_post_types['your_cpt_name'])){
        $wp_post_types['your_cpt_name']->exclude_from_search = true;
    }
}

Relatively simple, you create a function hooked into the init action. In this function, you’ll check for the existence of the (custom) post type in question, and when true, modify the post type definition object by setting the exclude from search property to true.

This is enough for tech-savvy users. But not for non-techie users.

First, you need to know the post type’s name and where to find it in WordPress.

Also, just like LearnDash, there is an N amount of plugins that add their own custom post types to WordPress.

The ideal solution I came up with is an admin page with a list of all the public (custom) post types registered in WordPress. These are retrieved dynamically and checked/unchecked depending on the value of the exclude_from_search property.

This gives users the power to decide what post type should appear on the search.

The disadvantage is that it may interfere with the functionality of plugins that need to appear in the search.