Created
January 7, 2018 20:32
-
-
Save tradesouthwest/dffd2a78bb5dd0416b19741f5c9f49ab to your computer and use it in GitHub Desktop.
wordpress filter for searching categories 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
<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