I created an AJAX category filter for a custom post type with custom taxonomy.
1)It's working but can't figure out how to add pagination for the custom taxonomy once it filters. When I click on pagination link 2 or 3 it takes to http://website.com/wp-admin/admin-ajax.php?paged=3
2) Can't figure out how to load ALL categories on page load
Here's my code so far:
Thanks
Custom.js
<script type="text/javascript">
//AJAX filter
function cat_ajax_get(catID) {
jQuery("a.ajax").removeClass("current");
jQuery("a.ajax").addClass("current"); //adds class current to the category menu item being displayed so you can style it with css
jQuery("#loading-animation").show();
var ajaxurl = "<?php echo esc_js( admin_url( 'admin-ajax.php' ) ) ?>";
jQuery.ajax({
type: 'POST',
url: ajaxurl,
data: {"action": "load-filter2", cat: catID },
success: function(response) {
jQuery("#category-post-content").html(response);
jQuery("#loading-animation").hide();
return false;
}
});
}
</script>
functions.php
<?php
add_action( 'wp_ajax_nopriv_load-filter2', 'prefix_load_term_posts' );
add_action( 'wp_ajax_load-filter2', 'prefix_load_term_posts' );
function prefix_load_term_posts () {
$cat_id = $_POST[ 'cat' ];
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'tax_query' => array(
array(
'taxonomy' => 'customtaxonomy',
'field' => 'term_id',
'terms' => array( $cat_id )
)
),
'post_type' => 'customPostType',
'posts_per_page' => 5,
'paged' => $paged
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<div>
<h3>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</h3>
</div>
<?php endwhile;?>
<nav class="pagination">
<?php
$big = 999999999; // need an unlikely integer
echo paginate_links( array(
'base' => str_replace( $big, '%#%', get_pagenum_link( $big ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
//'show_all' => true,
//'total' => 2,
'end_size' => 1,
'prev_next' => True,
'prev_text' => __('< Previous'),
'next_text' => __('Next >'),
'total' => $loop->max_num_pages
) );
?>
</nav>
feed-page.php
<?php
$args = array(
'hierarchical' => true,
'taxonomy' => 'customtaxonomy'
);
$categories = get_categories($args);?>
<div>
<?php foreach ( $categories as $cat ) { ?>
<div id="cat-<?php echo $cat->term_id; ?>"><a class="<?php echo $cat->slug; ?> ajax btn onclick="cat_ajax_get('<?php echo $cat->term_id; ?>');" href="#"><?php echo $cat->name; ?></a></div>
<?php } ?>
</div>
paged
query var or useget_pagenum_link
in the ajax request, you need to pass all required data with the ajax request, like you are doing with$cat_id
.