January 04, 2017
Using buttons and jQuery to filter and sort Posts on a website can be fun! Unfortunately, as your content grows, it can also become space consuming, and difficult to read.
Convert a list to a dropdown, and toggle the display of the items via class with a jQuery function.
Original HTML
<body> <div class="selectContainer"> <select id="theSelect"> <option value="">- Select -</option> <option value="Patient">Patient</option> <option value="Physician">Physician</option> <option value="Nurse">Nurse</option> </select> </div> <div class="isPatient">Patient</div> <div class="isPhysician">Physician</div> <div class="isNurse">Nurse</div> </body>
Original jQuery
$('[class^=is]').hide(); $("#theSelect").change(function(){ var value = $("#theSelect option:selected").val(); var theDiv = $(".is" + value); theDiv.slideDown(); theDiv.siblings('[class^=is]').slideUp(); });
Original content sourced here.
Customizations
You can modify the above to be dynamic by placing the select within a loop.
<select name="cat_filter" id="cat_filter"> <option value="all">All</option> <!-- include all value to display all content again --> <?php $args = array( 'taxonomy' => 'category' ); foreach (get_categories($args) as $category){ if ($category->count > 0){ ?> <option value="<?php echo $category->slug; ?>"> <?php echo $category->cat_name; ?></option> <?php } } ?> </select> <ul id="category_posts"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <li class="blog-filter isall <?php $my_terms = get_the_terms( $post->ID, 'category' ); // include "isall" for displaying all values, and additional class to dynamically hide items on change if( $my_terms && !is_wp_error( $my_terms ) ) { foreach( $my_terms as $term ) { ?> is<?php echo $term->slug; ?> <?php } } ?>"> <div class="blog_content"> <h2><?php the_title(); ?></h2> <?php the_excerpt(); ?> </div> </li> <?php endwhile; ?> <?php else : ?> <p><?php _e('Sorry, no blog posts to display.'); ?></p> <?php endif; ?> </ul>
Target the element, and hide excess on change:
jQuery("#cat_filter").change(function(){ var value = jQuery("#cat_filter option:selected").val(); jQuery('.blog-filter').hide(); // hide additional class items when change occurs var el = jQuery("#category_posts li.is" + value); el.slideDown(); });