Jak mogę jednocześnie uruchomić dwa żądania AJAX w WordPress?
Trochę utknąłem tutaj, pracując z AJAX i próbując wyświetlać posty na podstawie interakcji użytkownika. W tej chwili działam, gdy użytkownik wybiera listę rozwijaną kategorii, a posty ładują się odpowiednio. To, co chciałbym zrobić, to pójść o krok dalej i wypełnić kolejne menu rozwijane podkategoriami na podstawie wybranej kategorii nadrzędnej. Zobacz witrynę tutaj.
jQuery
$('#ajaxFilter select').on('change', function(event) {
if(event.preventDefault) { event.preventDefault(); }
$this = $(this);
$value = this.value;
$page = $this.data('page');
$term = $this.data('term');
$qty = $this.closest('#ajaxFilter').data('paged')
$params = {
//Bind parameters
'value': $value,
'page' : $page,
'term' : $term,
'qty' : $qty,
};
//Run the query with those parameters
get_posts($params);
});
function get_posts($params) {
$content = $('#ajaxPosts');
$.ajax({
url: psc.ajax_url,
data: {
action: 'filter_posts',
nonce: psc.nonce,
params: $params
},
type: 'post',
dataType: 'json',
success: function(data, textStatus, XMLHttpRequest) {
if (data.status === 200) {
$content.html(data.content);
}
else if (data.status === 201) {
$content.html(data.message);
}
else {
$status.html(data.message);
}
},
error: function(MLHttpRequest, textStatus, errorThrown) {
$status.html(textStatus);
}
});
}
funkcje.php
function psc_filter_posts() {
if( !isset( $_POST['nonce'] ) || !wp_verify_nonce( $_POST['nonce'], 'psc' ) )
die('Permission denied');
$value = intval($_POST['params']['value']);;
$term = sanitize_text_field($_POST['params']['term']);
$page = intval($_POST['params']['page']);
$qty = intval($_POST['params']['qty']);
if ( $value == 0 ) :
$tax_qry[] = [
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => $value,
'operator' => 'NOT IN'
];
else :
$tax_qry[] = [
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => $value,
];
endif;
//Setup the query args for wp query
$args = [
'paged' => $page,
'post_status' => 'publish',
'posts_per_page' => $qty,
'tax_query' => $tax_qry
];
$qry = new WP_Query($args);
ob_start();
if ($qry->have_posts()) : ?>
<div class="container">
<?php while ($qry->have_posts()) : $qry->the_post(); ?>
LOOP STUFF
<?php endwhile; ?>
</div><!-- .container -->
<nav class = "container mt-5 text-center">
<div class="row">
<div class="col-sm-12">
<?php psc_ajax_pager($qry,$page,$value); ?>
</div><!-- .col-sm-12 -->
</div><!-- .row -->
</nav>
<?php $response = [
'status'=> 200,
'found' => $qry->found_posts
];
else :
$response = [
'status' => 201,
'message' => 'No posts found'
];
endif;
$response['content'] = ob_get_clean();
die(json_encode($response));
}
add_action('wp_ajax_filter_posts', 'psc_filter_posts');
add_action('wp_ajax_nopriv_filter_posts', 'psc_filter_posts');