I have a page on which I want to display all posts of a specific custom post type, let's call it "persons". I want to allow the user to filter all persons by multiple (!) taxonomies: age, city, profession, level of experience. The best way to do that would be via clicking checkboxes and getting the results immediately via ajax without any page reload.
I think this is something many Wordpress developers want to realize. Unfortunately, I have not found any suitable tutorial for achieving this. But it must be something easy to do for experienced WordPress developers...
Can anyone provide a code template for how to build a filter page for the custom post type described above?
I already know how to filter posts by just ONE taxonomy, by jQuery. This is the code I used so far:
<!-- PAGE TEMPLATE FOR OVERVIEW OF ALL POSTS OF CUSTOM POST TYPE "PERSONS" -->
<!-- LIST OF ALL ENTRIES OF TAXONOMY "CITIES" -->
<div class="cities">
<a href="#" id="all">All cities</a>
<?php
// Get all terms of a taxonomy
$taxonomy = 'cities';
$terms = get_terms($taxonomy);
if ( $terms && !is_wp_error( $terms ) ) :
foreach ( $terms as $term ) { ?>
<a href="javascript:void(0);" data-target="<?php echo $term -> slug; ?>"><?php echo $term -> name; ?></a>
<?php } endif; ?>
</div>
<!-- OUTPUT PERSONS -->
<div class="overview_persons">
<?php
$args= array(
'post_type' => 'persons',
'post_status' => 'publish',
'meta_key' => 'zip',
'orderby' => 'meta_value_num',
'order' => 'ASC',
'posts_per_page' => -1
);
query_posts($args);
if ( have_posts() ) : while ( have_posts() ) : the_post();
$post_terms = wp_get_post_terms( $post->ID, $taxonomy, array( "fields" => "slugs" ) );
$post_terms_space_separated = implode(" ", $post_terms);
?>
<!-- output selected taxonomy value in class of person div -->
<div class="person <?php echo $post_terms_space_separated; ?>">
<!-- description of person -->
</div>
<?php endwhile; endif; wp_reset_query(); ?>
</div>
<!-- MY JQUERY FOR FILTERING PERSONS VIA TAXONOMY "CITY" -->
<script>
jQuery(document).ready(function() {
// Click on a city
jQuery('a[data-target]').click(function() {
jQuery('.person').show().not('.' + this.dataset.target).hide();
});
// Click on "All cities"
jQuery('#all').click(function(e) {
e.preventDefault();
jQuery('.person').show();
});
});
</script>
This code works perfectly fine. But my new challenge is filtering persons by more than one taxonomy - not only by the city, but also by the age, profession and level of experience. How do I need to modify my code for achieving this? Achieving this by Ajax would be the preferrable way, of course.