How to create a search by category in WordPress

In this article, you will come to know how to create a search by category in WordPress.

Let’s get started

<form role="search" method="get" class="envy-doc-widget-form search-form banner-search-form" action="<?php echo esc_url( home_url('/') ); ?>">
    <div class="row">
        <?php
        $envy_doc_query = array( 
            'post_type' => 'EnvyDoc', 
            'posts_per_page' => -1,
            'order' => 'ASC',
            'orderby' => 'menu_order',
            'post_parent' => 0
        );

        $envy_doc_loop = new \WP_Query( $envy_doc_query );
        ?>
        <script>
            function envy_doc_search_select() {
            let btnSend = document.querySelector('#envyDocSelect');
                if (btnSend) {
                    btnSend.setAttribute('name', 's');
                }
            }
        </script>
            <div class="col-lg-9 col-md-8">
                <?php if( $settings['search_placeholder'] != '' ): ?>
                    <div class="form-group">
                        <label>
                            <i class='bx bx-search'></i>
                        </label>
                        <input type="search" value="<?php get_search_query(); ?>"  name="s" class="form-control" placeholder="<?php echo wp_kses_post( $settings['search_placeholder'] ); ?>"/>
                    </div>
                <?php endif; ?>
            </div>
            <div class="col-lg-3 col-md-4">
                <div class="form-group">
                    <input type="hidden" name="post_type" value="envydoc"/>
                    <select id="envyDocSelect" onchange="envy_doc_search_select()" class="form-select">
                            <option>
                                <?php echo esc_html__('All Docs', 'doca'); ?>
                            </option>
                            <?php 
                                while ( $envy_doc_loop->have_posts() ) : $envy_doc_loop->the_post(); ?>
                                <option><?php the_title(); ?></option>
                            <?php endwhile; ?>
                        </select>
                </div>
            </div>
            <div class="col-lg-12 col-md-12">
            <?php if( $settings['button_text'] ): ?>
                <button type="submit" class="search-btn"><?php echo wp_kses_post( $settings['button_text'] ); ?></button>
            <?php endif; ?>
            </div>
    </div>
</form>

 

That’s it. Hope this is helpful to you

Happy Coding! Thanks

 

Leave a Reply

Your email address will not be published. Required fields are marked *