Last active
September 7, 2022 11:17
-
-
Save Bobz-zg/f7625da1481c9fee3c8cfd1bb1b5f569 to your computer and use it in GitHub Desktop.
Filter WordPress posts by custom taxonomy term with AJAX
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Spot on Mr. @mail2ssr , thank you