1

I have a list of category children in a form, I am hoping to have the user select all the subcategories they want to include in their search results. Once the user hits submit, they would be taken to another page with the results.

<form>
     <?php
        $args = array(
            'taxonomy'      => 'category',
            'parent'        => 0, // get top level categories
            'orderby'       => 'name',
            'order'         => 'ASC',
            'hierarchical'  => 1,
            'pad_counts'    => 0
        );

        $categories = get_categories( $args );

        foreach ( $categories as $category ){
            echo '<div class="search-box">';
                echo '<div class="search-box-inside">';
                    echo '<h4>'. $category->name . '</h4>';

                    $sub_args = array(
                        'taxonomy'      => 'category',
                        'parent'        => $category->term_id, // get child categories
                        'orderby'       => 'name',
                        'order'         => 'ASC',
                        'hierarchical'  => 1,
                        'pad_counts'    => 0
                    );

                    $sub_categories = get_categories( $sub_args );

                    foreach ( $sub_categories as $sub_category ){

                        echo '<label><input type="checkbox" id="type-'. $sub_category->name . '" rel="'. $sub_category->name . '">'. $sub_category->name . '</label>';

                    }
                echo '</div>';
            echo '</div>';

        }
        ?>
            <input type="submit" value="Submit">
            </form>

So far I am able to echo a list of the subcategories with checkboxes, but how do I feed the checkbox values into a searchable query so I can get all the subcategories that were selected?

0

The scope of your question is pretty broad, but I think I can help. Set the name to as the same name for the ones you want grouped using array syntax ([]). Set the checkboxes' values to the category ID.

// ...
foreach ( $sub_categories as $sub_category ){    
    echo '<label><input type="checkbox" id="type-'. $sub_category->name . '" rel="'. $sub_category->name . '" name="subcats[]" value="' . $sub_category->term_id .'">'. $sub_category->name . '</label>';
}
// ...

Then, supposing your form's method is POST, you would retrieve the results on the destination page specified in the form's action parameter. So, on search results page:

$subcategories = $_POST['subcats'];

// You could then use the array of category ID's to do a WP_Query, for example:
$category_search_results = new WP_Query([
    'category__in' => $subcategories
]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.