Search only posts (not pages) in WordPress

To search for only posts (not pages) in WordPress, you can make use of the pre_get_posts filter and modify the main query before it is executed. Here’s an example of how you can achieve this:

1. Open the theme’s functions.php file in your WordPress theme directory.
2. Add the following code to the file:

 

function exclude_other_post_from_search($query) {
    if (is_search() && !is_admin()) {
        $query->set('post_type',array('post','page'));
    }
}
add_action('pre_get_posts', 'exclude_other_post_from_search');

3. Save the changes and upload the modified functions.php file back to your server.

 

This code hooks into the pre_get_posts action and modifies the query’s post_type parameter to include only posts when a search is being performed and not when the request is made from the WordPress admin area.

After making these changes, the search results will only display posts and pages, excluding any other post type from the results.

Related Blogs

How To Limit Search To Only Post Titles?

I added a text field to the posts filter form and I use s= parameter to make the search work. But how to search only in the title of the post (not in the content)? how to limit search to post titles? How to search only by Post Title?

Fetch WordPress Categories

Fetch wordpress categories Using inbuilt functions like get_categories(), wp_list_categories(), wp_dropdown_categories().

Add same product to cart twice instead of changing quantity in Cart

By default, WooCommerce allows customers to change the quantity of a product in the cart by updating the quantity input field on the cart page. If the quantity is increased, the product will be added to the cart only once with the updated quantity. However, if you want to allow customers to add the same product multiple times as separate items in the cart, you’ll need to customize the cart behavior.

Request A Quote

Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.