Easy jQuery Data Filter

Super simple jQuery data filter, that can easily be made dynamic using a query like so:

HTML (plus PHP):

<ul id="career_categories">
 <?php 
 
 $args = array(
 'taxonomy' => 'career_category'
 );
 
 foreach (get_categories($args) as $category) { ?>
 <li><a href="javascript:void(0);" id="<?php echo $category->slug; ?>"><?php echo $category->name; ?></a></li>
 <?php }  ?>
</ul><!-- #career_categories -->


<div id="careers">
 <?php $args = array(
 'post_type' => 'career',
 'posts_per_page' => -1
 );
 
 $career = get_posts($args);
 
 foreach($career as $post) : setup_postdata($post); ?>
 
 <div class="career_filter <?php $class_terms = get_the_terms( $post->ID, 'career_category' );
 if( $class_terms && !is_wp_error( $class_terms ) ) {
 foreach( $class_terms as $class ) {
 ?> <?php echo $class->slug; ?>
 <?php } } ?>">
 <h2 class="career_title"><?php the_title(); ?>
 <span><?php $class_terms = get_the_terms( $post->ID, 'career_category' );
 if( $class_terms && !is_wp_error( $class_terms ) ) {
 foreach( $class_terms as $class ) {
 ?> <?php echo $class->name; ?> | 
 <?php } } ?><a href="<?php echo get_permalink(249); ?>"><?php echo get_the_title(249); ?></a></span>
 </h2>
 <?php the_content(); ?>
 </div>
 
 <?php endforeach; wp_reset_postdata(); ?>
</div><!-- #careers -->

jQuery:

jQuery('#career_categories li a').click(function(e){ 

 //prevent the default behaviour of the link 
 e.preventDefault(); 

 //get the id of the clicked link(which is equal to classes of our content 
 var filter = jQuery(this).attr('id'); 

 //show all the list items(this is needed to get the hidden ones shown) 
 jQuery('#careers .career_filter').show(); 

 /*using the :not attribute and the filter class in it we are selecting 
 only the list items that don't have that class and hide them '*/ 
 jQuery('#careers .career_filter:not(.' + filter + ')').hide(); 

});


Sourced here.

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.