Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save huubl/13f33641f3e885a0bda85e48154408ee to your computer and use it in GitHub Desktop.
Save huubl/13f33641f3e885a0bda85e48154408ee to your computer and use it in GitHub Desktop.
wordpress filter for searching categories with ajax
<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">
<?php
if( $terms = get_terms( 'category', 'orderby=name' ) ) :
echo '<select name="categoryfilter"><option>Select category...</option>';
foreach ( $terms as $term ) :
echo '<option value="' . $term->term_id . '">' . $term->name . '</option>';
endforeach;
echo '</select>';
endif;
?>
<label>
<input type="radio" name="date" value="ASC" /> Date: Ascending
</label>
<label>
<input type="radio" name="date" value="DESC" selected="selected" /> Date: Descending
</label>
<button>Apply filters</button>
<input type="hidden" name="action" value="customfilter">
</form>
<div id="response"></div>
<script>jQuery(function($){
$('#filter').submit(function(){
var filter = $('#filter');
$.ajax({
url:filter.attr('action'),
data:filter.serialize(), // form data
type:filter.attr('method'), // POST
beforeSend:function(xhr){
filter.find('button').text('Applying Filters...'); },
success:function(data){
filter.find('button').text('Apply filters'); $('#response').html(data);
}
});
return false;
});
});</script>
<?php
function my_filters(){
$args = array(
'orderby' => 'date',
'order' => $_POST['date']
);
if( isset( $_POST['categoryfilter'] ) )
$args['tax_query'] = array(
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => $_POST['categoryfilter']
)
);
$query = new WP_Query( $args );
if( $query->have_posts() ) :
while( $query->have_posts() ): $query->the_post();
echo '<h2>' . $query->post->post_title . '</h2>';
endwhile;
wp_reset_postdata();
else :
echo 'No posts found';
endif;
die();
}
add_action('wp_ajax_customfilter', 'my_filters');
add_action('wp_ajax_nopriv_customfilter', 'my_filters');
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment