I have a working php ajax form, including pulling data from acf. I can't figure how to filter by checked checkbox items. so if a user checks one/multiple items in the form front end, it would match posts with the same field choices checked. It does work for me if i'm using a select dropdown instead of a checkbox items in the form. My checkbox field is 'weather'.
Here is my form:
<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">
<?php
$weather_values = get_field('weather');
if( $weather_values ): ?>
<?php foreach( $weather_values as $weather ): ?>
<input type="checkbox" name="<?php echo $weather; ?>"><?php echo $weather; ?>
<?php endforeach; ?>
<?php endif;
?>
<button>Apply filter</button>
<input type="hidden" name="action" value="myfilter">
</form>
Here is js:
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('Processing...'); // changing the button label
},
success:function(data){
filter.find('button').text('Apply filter'); // changing the button label back
$('#response').html(data); // insert data
}
});
return false;
});
});
Here is the functions.php
//ajax form submit function
add_action('wp_ajax_myfilter', 'form_filter_function'); // wp_ajax_{ACTION HERE}
add_action('wp_ajax_nopriv_myfilter', 'form_filter_function');
function form_filter_function(){
// create $args['meta_query'] array if one of the following fields is filled
if( isset( $_POST['weather'] ) && $_POST['weather'] == 'on' )
$args['meta_query'] = array( 'relation'=>'AND' );
if( isset( $_POST['weather'] ) )
$args['meta_query'][] = array(
'key' => 'weather',
'value' => $_POST['weather'],
'compare' => 'LIKE'
);
$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();
}
So right now doesn't matter what I check or if I even check something, all posts are showing.
Aucun commentaire:
Enregistrer un commentaire