Last active
September 29, 2016 09:24
-
-
Save Bobz-zg/366e06ca428e6e86cc05e53b15b1bb68 to your computer and use it in GitHub Desktop.
Filter WordPress posts by custom taxonomy term with AJAX
This file contains 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 | |
function vb_filter_posts() { | |
if( !isset( $_POST['nonce'] ) || !wp_verify_nonce( $_POST['nonce'], 'bobz' ) ) | |
die('Permission denied'); | |
/** | |
* Default response | |
*/ | |
$response = [ | |
'status' => 500, | |
'message' => 'Something is wrong, please try again later ...', | |
'content' => false, | |
'found' => 0 | |
]; | |
$tax = sanitize_text_field($_POST['params']['tax']); | |
$term = sanitize_text_field($_POST['params']['term']); | |
$page = intval($_POST['params']['page']); | |
$qty = intval($_POST['params']['qty']); | |
/** | |
* Check if term exists | |
*/ | |
if (!term_exists( $term, $tax) && $term != 'all-terms') : | |
$response = [ | |
'status' => 501, | |
'message' => 'Term doesn\'t exist', | |
'content' => 0 | |
]; | |
die(json_encode($response)); | |
endif; | |
/** | |
* Tax query | |
*/ | |
if ($term == 'all-terms') : | |
$tax_qry[] = [ | |
'taxonomy' => $tax, | |
'field' => 'slug', | |
'terms' => $term, | |
'operator' => 'NOT IN' | |
]; | |
else : | |
$tax_qry[] = [ | |
'taxonomy' => $tax, | |
'field' => 'slug', | |
'terms' => $term, | |
]; | |
endif; | |
/** | |
* Setup query | |
*/ | |
$args = [ | |
'paged' => $page, | |
'post_type' => 'post', | |
'post_status' => 'publish', | |
'posts_per_page' => $qty, | |
'tax_query' => $tax_qry | |
]; | |
$qry = new WP_Query($args); | |
ob_start(); | |
if ($qry->have_posts()) : | |
while ($qry->have_posts()) : $qry->the_post(); ?> | |
<article class="loop-item"> | |
<header> | |
<h2 class="entry-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> | |
</header> | |
<div class="entry-summary"> | |
<?php the_excerpt(); ?> | |
</div> | |
</article> | |
<?php endwhile; | |
/** | |
* Pagination | |
*/ | |
vb_ajax_pager($qry,$page); | |
$response = [ | |
'status'=> 200, | |
'found' => $qry->found_posts | |
]; | |
else : | |
$response = [ | |
'status' => 201, | |
'message' => 'No posts found' | |
]; | |
endif; | |
$response['content'] = ob_get_clean(); | |
die(json_encode($response)); | |
} | |
add_action('wp_ajax_do_filter_posts', 'vb_filter_posts'); | |
add_action('wp_ajax_nopriv_do_filter_posts', 'vb_filter_posts'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment