Greenhoe
Greenhoe

Reputation: 1051

Create filters for wordpress categories

I created a card database which you can see here http://hearthable.com/cards. I did this in wordpress via a custom post type. I have over 400+ cards. I also have 4 custom post type categories / taxonomies.

My custom post type is named "cards" and the 4 custom taxonomies are "cards-type", "cards-rarity", and "cards-class", "cards-race".

I wanted to add a filter feature where my users can click on a checkbox next to one, 2 or 3 of those categories and filter the cards based off their selection.

I've been looking all over and couldn't find anything on this so a little help would be greatly appreciative. Thank you.

Upvotes: 0

Views: 165

Answers (1)

Marcos Rodrigues
Marcos Rodrigues

Reputation: 712

I've made a quick example, just to show you how the filters would work. it can be improved and can be done with other ways.

You Have to create a form and set a page (i've hardcoded, you can do it better)

<form action="/sample-page/" method="post">

    <?php 
        wp_dropdown_categories( array(
        'show_option_all'    => 'All',
        'show_option_none'   => 'None',
        'show_count'         => 0,
        'hide_empty'         => 0, 
        'exclude'            => '',
        'echo'               => 1,
        'name'               => 'cards-type',
        'id'                 => '',
        'class'              => 'postform',
        'taxonomy'           => 'cards-type',
        'hide_if_empty'      => false,
    ) );

    wp_dropdown_categories( array(
        'show_option_all'    => 'All',
        'show_option_none'   => 'None',
        'show_count'         => 0,
        'hide_empty'         => 0, 
        'exclude'            => '',
        'echo'               => 1,
        'name'               => 'cards-rarity',
        'id'                 => '',
        'class'              => 'postform',
        'taxonomy'           => 'cards-rarity',
        'hide_if_empty'      => false,
    ) );

    ?>

    <button type="submit">Go</button>
</form>

In the page you set you have to get the data and transform it in array for WP_Query

    $args = array(
        'post_type' => 'cards', 
    );

    $item = array();
    $list = array();

    if ( $_POST ) {
        foreach( $_POST as $key => $value ) {
            if( !empty($value) ) {
                $item['taxonomy'] = htmlspecialchars($key);
                $item['terms'] = htmlspecialchars($value);
                $item['field'] = 'id';
                $list[] = $item;
            }
            $cleanArray = array_merge(array('relation' => 'AND'), $list);
        }  

        $args['tax_query'] = $cleanArray;   
    }

    $loooop = new WP_Query( $args );

You use the loop to iterate the results

if ( $loooop->have_posts() ) : while ( $loooop->have_posts() ) : $loooop->the_post();
    the_title();
endwhile;
wp_reset_postdata();

Sorry for bad english

Upvotes: 1

Related Questions