Search Functionality

We will discuss search functionality in this lecture. WordPress gives us prebuilt functionality, But we will fully customize it. Firstly add more blogs, create more categories, and add tags too. get_search_form is a helper method to get the search form, Which routes search.php file.

Get Search Form
Add below helper method, where ever you the want to show search bar.

<?php
   get_search_form();
?>

 

Global Search
WordPress also allows us to create our custom forms. So, create searchform.php file and create the form there.

<form action="<?php echo home_url();?>/" method="get">

    <label for="search">Search</label><br>
    <input type="text" name="s" id="search" value="<?php the_search_query( ); ?>" required>

    <button type="submit">Search</button>

</form>

 

Search Form for Specific Category
Below search form for specific tags & categories by using Id in searchform.php file.

<form action="<?php echo home_url(); ?>/" method="get">

    <!-- Add category ID in value -->
    <input type="hidden" name="cat" value="9">

    <label for="search">Search</label><br>
    <input type="text" name="s" id="search" value="<?php the_search_query( ); ?>" required>

    <button type="submit">Search</button>

</form>

 

After searching you will see its routes index.php if you don’t have  search.php. so, we will create search.php file to get search results.

Search.php File

adds the below code in search.php file.

<?php get_header(); ?>

<div class="container pt-5">
    <div class="row">

        <h1>Search Result "<?php echo the_search_query(); ?>"</h1>

        <?php if( have_posts( ) ): while( have_posts() ): the_post( ); ?>
            <div class="col-md-4">

                <div class="card">
                    <?php if(has_post_thumbnail()) : ?>
                        <img src="<?php the_post_thumbnail_url(); ?>" class="card-img-top" alt="<?php the_post_thumbnail_caption(); ?>">
                    <?php endif; ?>
                    <div class="card-body">
                        <h5 class="card-title"><?php the_title(); ?></h5>
                        <p class="card-text"><?php the_excerpt( ); ?></p>
                        <a href="<?php the_permalink( ); ?>" class="btn btn-primary">Explore More</a>
                    </div>
                </div>

            </div>
        <?php endwhile; else: ?>
            There are no results for '<?php echo get_search_query(); ?>'    
        <?php endif; ?>

    </div>
</div>

<?php get_footer(); ?>

 

#BeingCodeStuffer

Related Theme Developments