Attaching category queries to search field

Question

I’m trying to filter the loop based on some category buttons, so when someone clicks the button the search results are filtered. However, I can’t seem to pass the category to the search results.

Here is the query function in functions.php:
poet_category_button_query()

function poet_category_button_query( $category ) {
    global $category_query;
    
    return $category_query = get_posts( array( 'category_name' => $category ) );
};

Here is the PHP for the search & category buttons:
searchform.php

<form role='search' method='get' class='search-form' action='<?php echo home_url( '/' ); ?>'>
    <div class='search-wrapper'>
        <label>
            <span class='screen-reader-text'><?php echo _x( 'Search for:', 'label' ) ?></span>
            <input type='search' class='search-field'
                placeholder='<?php echo esc_attr_x( 'Search...', 'placeholder' ) ?>'
                value='<?php echo get_search_query() ?>' name='s'
                title='<?php echo esc_attr_x( 'Search for:', 'label' ) ?>' />
        </label>
        <input type='submit' class='search-submit'
            value='<?php echo esc_attr_x( 'Search', 'submit button' ) ?>' />
    </div>
    <h2 class='categories-header'>Categories</h2>
    <div class='categories-wrapper'>
        <?php
            $categories = get_categories( array(
                'orderby' => 'name',
                'order' => 'ASC',
                'hide_empty' => false
                ) );
                
            foreach( $categories as $category ) {
                printf(
                    '<input
                        class="category-button"
                        type="button"
                        value="%2$s"
                        onclick="%3$s"
                    >',
                    esc_url( get_category_link( $category->term_id ) ),
                    esc_html( $category->name ),
                    poet_category_button_query( $category->name )
                );
            };
        ?>
    </div>
</form>
0
Yusuf Abukar 4 months 0 Answers 8 views 0

Leave an answer