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

Add Custom Product Data Tab

Learn how to enhance your WooCommerce product editor by adding a custom product data tab. Follow a step-by-step guide using the woocommerce_product_data_tabs filter and the woocommerce_product_data_panels action. Create a custom tab with your desired label, and include your own fields or content within the panel. Customize your product data to collect and display additional information, providing a tailored experience for your WooCommerce products.

Add Custom Price on Bulk Purchase in Woocommerce Using ACF

To achieve this functionality, you’ll need to create a custom ACF repeater field for quantity and price in the product admin panel and then display all the prices on the product single page. Additionally, you’ll have to calculate the price according to the selected quantity when a product is added to the cart using WordPress hooks.