Skip to content

Instantly share code, notes, and snippets.

@Bobz-zg
Last active November 14, 2016 08:11
Show Gist options
  • Save Bobz-zg/7883f7f12f9fe10380e82bebabac43f0 to your computer and use it in GitHub Desktop.
Save Bobz-zg/7883f7f12f9fe10380e82bebabac43f0 to your computer and use it in GitHub Desktop.
Filter WordPress posts by multiple taxonomy terms with AJAX and pagination
<?php
function vb_filter_posts_mt() {
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
];
$terms = $_POST['params']['terms'];
$page = intval($_POST['params']['page']);
$qty = intval($_POST['params']['qty']);
$pager = isset($_POST['pager']) ? $_POST['pager'] : 'pager';
$tax_qry = [];
$msg = '';
/**
* Check if term exists
*/
if (!is_array($terms)) :
$response = [
'status' => 501,
'message' => 'Term doesn\'t exist',
'content' => 0
];
die(json_encode($response));
else :
foreach ($terms as $tax => $slugs) :
$tax_qry[] = [
'taxonomy' => $tax,
'field' => 'slug',
'terms' => $slugs,
];
endforeach;
endif;
/**
* Setup query
*/
$args = [
'paged' => $page,
'post_type' => 'any',
'post_status' => 'published',
'posts_per_page' => $qty,
];
if ($tax_qry) :
$args['tax_query'] = $tax_qry;
endif;
$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
*/
if ( $pager == 'pager' )
vb_ajax_pager($qry,$page);
foreach ($tax_qry as $tax) :
$msg .= 'Displaying terms: ';
foreach ($tax['terms'] as $trm) :
$msg .= $trm . ', ';
endforeach;
$msg .= ' from taxonomy: ' . $tax['taxonomy'];
$msg .= '. Found: ' . $qry->found_posts . ' posts';
endforeach;
$response = [
'status' => 200,
'found' => $qry->found_posts,
'message' => $msg,
'method' => $pager,
'next' => $page + 1
];
else :
$response = [
'status' => 201,
'message' => 'No posts found',
'next' => 0
];
endif;
$response['content'] = ob_get_clean();
die(json_encode($response));
}
add_action('wp_ajax_do_filter_posts_mt', 'vb_filter_posts_mt');
add_action('wp_ajax_nopriv_do_filter_posts_mt', 'vb_filter_posts_mt');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment