Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Filter WordPress posts by custom taxonomy term with AJAX
* Shortocde for displaying terms filter and results on page
function vb_filter_posts_sc($atts) {
$a = shortcode_atts( array(
'tax' => 'post_tag', // Taxonomy
'terms' => false, // Get specific taxonomy terms only
'active' => false, // Set active term by ID
'per_page' => 12 // How many posts per page,
'pager' => 'pager' // 'pager' to use numbered pagination || 'infscr' to use infinite scroll
), $atts );
$result = NULL;
$terms = get_terms($a['tax']);
if (count($terms)) :
ob_start(); ?>
<div id="container-async" data-paged="<?php echo $a['per_page']; ?>" class="sc-ajax-filter">
<ul class="nav-filter">
<a href="#" data-filter="<?= $terms[0]->taxonomy; ?>" data-term="all-terms" data-page="1">
Show All
<?php foreach ($terms as $term) : ?>
<li<?php if ($term->term_id == $a['active']) :?> class="active"<?php endif; ?>>
<a href="<?php echo get_term_link( $term, $term->taxonomy ); ?>" data-filter="<?php echo $term->taxonomy; ?>" data-term="<?php echo $term->slug; ?>" data-page="1">
<?php echo $term->name; ?>
<?php endforeach; ?>
<div class="status"></div>
<div class="content"></div>
<?php if ( $a['pager'] == 'infscr' ) : ?>
<nav class="pagination infscr-pager">
<a href="#page-2" class="btn btn-primary">Load More</a>
<?php endif; ?>
<?php $result = ob_get_clean();
return $result;
add_shortcode( 'ajax_filter_posts', 'vb_filter_posts_sc');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment