Add Search Functionality to a Website

Posted on Mar 20, 2025

by Jimmy

Last updated on December 4, 2025


Some code to get a basic search functionality going for your project.

Step 1

Add the search.php template in the root folder:

PHP
        
            <?php get_header(); ?>

<?php get_template_part('inc/hero'); ?>

<section class="flexible-content">

    <div class="flexible-content__container">

        <!-- WP loop -->
        <?php if( have_posts() ) : ?>

            <div class="tm-search-results">

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

                    <a class="search-result" href="<?php the_permalink(); ?>">
                        <h2 class="search-result__title"><?php the_title(); ?></h2>
                        <?php if( tm_flexible_excerpt($post->ID) ) : ?>
                            <p class="search-result__excerpt"><?= tm_flexible_excerpt($post->ID); ?></p>
                        <?php endif; ?>
                    </a>

                <?php endwhile; ?>

            </div><!-- END tm-search-results -->

            <?php else : ?>

            <p>Sorry, no search results could be found for the query:<strong> “ <?= get_search_query(); ?> ”</strong>, please try another search.</p>

        <?php endif; ?>

    </div><!-- END flexible-content__container -->

</section>

<?php get_footer(); ?>        
    

Step 2

Add searchform.php to your root folder:

PHP
        
            <form action="<?= home_url(); ?>" method="get" class="search-form">

    <label class="hidden--visually" for="search">Search</label>
    <div class="search-form__group">
        <input class="search-form__term" type="text" name="s" id="search" value="<?php the_search_query(); ?>" placeholder="Search..." required>
        <button class="search-form__submit" type="submit">Search</button>
    </div>

</form>        
    

Step 3

Include the search form template wherever needed:

PHP
        
            <?php get_template_part('searchform'); ?>        
    

Back to Snippets