Restrict Search Results for Posts Only

Astra provides a search option within a website along with few styles. When a user searches for some string, results are served from the entire website. In case you wish to restrict search results for posts only use the following custom code.

It will execute search query withing posts only.

Note: Add the following code in the child theme’s functions.php file.

add_action( 'wp', 'astra_modify_search_loop', 99 );

/**
* Modify Search Loop.
*
* @return void
*/
function astra_modify_search_loop() {
    remove_action( 'astra_content_loop', array( Astra_Loop::get_instance(), 'loop_markup' ) );
    add_action( 'astra_content_loop', 'astra_redo_loop_markup' );
}

/**
* Redo loop to search only posts.
*
* @return void
*/
function astra_redo_loop_markup() {

    global $post;

    ?>
    <main id="main" class="site-main" role="main">

        <?php if ( have_posts() ) : ?>

            <?php do_action( 'astra_template_parts_content_top' ); ?>

            <?php
            while ( have_posts() ) :
                the_post();

                if ( is_search() && ( 'page' == $post->post_type ) ) {
                    continue;
                }

                if ( true == $is_page ) {
                    do_action( 'astra_page_template_parts_content' );
                } else {
                    do_action( 'astra_template_parts_content' );
                }

                ?>

            <?php endwhile; ?>

            <?php do_action( 'astra_template_parts_content_bottom' ); ?>

        <?php else : ?>

            <?php do_action( 'astra_template_parts_content_none' ); ?>

        <?php endif; ?>

    </main><!-- #main -->
    <?php
}
Not the solution you are looking for? Check other articles, or open a support ticket.