Pawan Kumawat

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.

Categories

Related Blogs

Cron Job WordPress (WP-Cron)

What Is Wordpress Cron Job? Wordpress Cron Job is how WordPress handles scheduling time-based tasks in WordPress.“Cron” Means the cron time-based task scheduling system which is available on UNIX systems.