Skip to content

Instantly share code, notes, and snippets.

@Bobz-zg
Last active September 7, 2022 11:17
Show Gist options
  • Save Bobz-zg/f7625da1481c9fee3c8cfd1bb1b5f569 to your computer and use it in GitHub Desktop.
Save Bobz-zg/f7625da1481c9fee3c8cfd1bb1b5f569 to your computer and use it in GitHub Desktop.
Filter WordPress posts by custom taxonomy term with AJAX
<?php
/**
* 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">
<li>
<a href="#" data-filter="<?= $terms[0]->taxonomy; ?>" data-term="all-terms" data-page="1">
Show All
</a>
</li>
<?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; ?>
</a>
</li>
<?php endforeach; ?>
</ul>
<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>
</nav>
<?php endif; ?>
</div>
<?php $result = ob_get_clean();
endif;
return $result;
}
add_shortcode( 'ajax_filter_posts', 'vb_filter_posts_sc');
@mail2ssr
Copy link

mail2ssr commented Sep 7, 2022

on this line, 'per_page' => 12 // How many posts per page,

we need comma after 12 like this

'per_page' => 12, // How many posts per page,

@Bobz-zg
Copy link
Author

Bobz-zg commented Sep 7, 2022

Spot on Mr. @mail2ssr , thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment