Restricts Search Results to Blog Posts

Restricts search results to only include blog posts.

PHP
/**
 * Snippet Name:     Restricts search results to blog posts
 * Snippet Author:   coding-bunny.com
 * Description:      Restricts search results to only include blog posts.
 */

if (!is_admin()) {
    /**
     * Custom search filter to limit results to posts only.
     *
     * @param WP_Query $query The WP_Query instance (passed by reference).
     */
    function cb_limit_search_to_posts($query) {
        // Check if it's the main query and a search request
        if ($query->is_main_query() && $query->is_search()) {
            // Limit the search to only return posts
            $query->set('post_type', 'post');
        }
    }
    
    // Hook the custom filter into the 'pre_get_posts' action
    add_action('pre_get_posts', 'cb_limit_search_to_posts');
}

How To Implement This Solution?

Leave a Reply

Your email address will not be published. Required fields are marked *

My Agile Privacy
This site uses technical and profiling cookies. You can accept, decline or customize cookies by pressing the desired buttons. By closing this policy you will continue without accepting.

Need help?

Choose one of the following options:

Powered by CodingBunny