Here is My code, it should be filtering by category, it displays all posts on any checkbox I click, I don’t know how to fix this, I have tried everything.
<form id="filter"> <?php if( $ terms = get_terms( 'category', 'orderby=name' ) ) : // to make it simple I use default categories foreach ( $ terms as $ term ) : echo '<input type="checkbox" name="category[]" value="' . $ term->term_id . '" class="br">' . $ term->name; echo ''; endforeach; endif; ?> <div class="filter-output"></div> </form>
Here is the js (coded inside a template page)
jQuery('#filter .br').click(function(){ // Declaratie van array var choices = {}; jQuery('.contents').remove(); jQuery('.filter-output').empty(); jQuery('input[type=checkbox]:checked').each(function() { if (!choices.hasOwnProperty(this.name)) choices[this.name] = [this.value]; else choices[this.name].push(this.value); }); console.log(choices); jQuery.ajax({ url: '<?php echo admin_url('admin-ajax.php'); ?>', type :'POST', data : { 'action' : 'call_post', // Naam van de PHP functie 'choices' : choices, }, success: function (result) { jQuery('.filter-output').append(result); // Voor testen - Resultaat (Kan later verwijderd worden) //console.log(Resultaat); //console.log(Keuzes); }, error: function(err){ // Voor testen - Error (Kan later verwijderd worden) console.log(err); console.log(choices); } }); })
funstions.php
add_action('wp_ajax_call_post', 'call_post'); add_action('wp_ajax_nopriv_call_post', 'call_post'); function call_post(){ // Verkijgen van AJAX data: $ choices = $ _POST['choices']; $ meta_query = array('relation' => 'OR'); foreach($ choices as $ Key=>$ Value){ if(count($ Value)){ foreach ($ Value as $ Inkey => $ Invalue) { $ meta_query[] = array( 'key' => $ Key, 'value' => $ Invalue, 'compare' => '=' ); } } } $ args = array( 'post_type' => 'post', 'meta_query' =>$ meta_query ); $ query = new WP_Query($ args); //if( ! empty ($ params['template'])) { ////$ template = $ params['template']; if( $ query->have_posts() ) : while( $ query->have_posts() ): $ query->the_post(); the_title(); endwhile; wp_reset_query(); else : wp_send_json($ query->posts); endif; //} die(); }
Anyone please help, I have been trying to make this work since yesterday and with no luck at all