Filter Content with HTML Select

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

    <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>
    <div class="isPatient">Patient</div>
    <div class="isPhysician">Physician</div>
    <div class="isNurse">Nurse</div>

Original jQuery


    var value = $("#theSelect option:selected").val();
    var theDiv = $(".is" + value);

Original content sourced here.


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 -->
	$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 }
	} ?>					

<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(); ?>
    <?php endwhile; ?>
    <?php else : ?>
	<p><?php _e('Sorry, no blog posts to display.'); ?></p>
  <?php endif; ?>

Target the element, and hide excess on change:

    var value = jQuery("#cat_filter option:selected").val();
    jQuery('.blog-filter').hide(); // hide additional class items when change occurs
    var el = jQuery("#category_posts" + value);


Leave a Reply

katherine as a flat graphic icon

About Me

I’m an African / Ojibwe First Nations Web Developer living in Winnipeg, Manitoba.

Visit the Tips and Blog to see what I’m working on.