Search WordPress Posts Only (and Exclude Other Pages)

by

In this quick tutorial, you’ll learn how to show only posts in your WordPress search results. In other words, all other pages, categories, and tags will be excluded from your site search.

By default, WordPress search queries all content including pages and posts. In many cases, bloggers want to exclude pages from their search results.

With a few lines of easy code, this fix can be quickly implemented on your WordPress website. Don’t let the fact that we’re working with code scare you. I’ll walk you through the process step-by-step.

WordPress site search only posts

Search WordPress Posts Only

The following code will return just posts when a site search is conducted on a WordPress website.

// show posts in search result
add_filter( 'generate_navigation_search_output', function() {
    printf(  
        '<form method="get" class="search-form navigation-search" action="%1$s">
            <input type="search" class="search-field" value="%2$s" name="s" title="%3$s" />
            <input type="hidden" name="post_type" value="post" />
        </form>', 
        esc_url( home_url( '/' ) ), 
        esc_attr( get_search_query() ),   
        esc_attr_x( 'Search', 'label', 'generatepress' ) 
    ); 
} );

The recommended place to insert this snippet of code is within a child theme, specifically in the function.php file. If you’re using GeneratePress, I have a detailed tutorial here on installing a child theme for GeneratePress.

Another option is to use a plugin like Code Snippets which allows you to run PHP code on your website. You never want to edit your theme directly as this comes with a risk of breaking things. It’s much safer to use a plugin or work within your child theme instead.

After inserting the above code, save your changes. Now when you perform a site search, pages are excluded from the results.

If you have any questions about filtering WordPress site search results, let me know in the comments below. I know a lot of times, bloggers are a bit timid to add code to their website. Don’t worry, if you follow the steps above, I assure you that you won’t break anything.

If you found this blog posts valuable, subscribe to my YouTube channel for all my latest WordPress video tutorials and walkthroughs. My goal is to help website owners like you avoid having to pay thousands of dollars to hire a web developer though my free content.

About The Author

With a strong software engineering background, Tony is determined to help as many people as possible start their online busines. Discover why Tony quit his hedge fund job to pursue this mission. You can send Tony a message here.

Leave a Comment