Answer the question
In order to leave comments, you need to log in
How to convert WordPress post filter to AJAX?
Good day to all.
Let's say I put together a filter for wordpress posts.
Most of it is here: dontforget.pro/wordpress/filtr-postov-po-proizvoln...
Now I want this filter to work on AJAX, and the only similar article was found here: https://misha.blog/wordpress/filtryi -zapisey-i-tov...
So now I have the form code:
<form class="filter" action="/wp-admin/admin-ajax.php" method="get">
<span><label>Цена от: <!-- Интервал значений цены -->
<input type="number" name="price_ot">
</label>
<label>до:
<input type="number" name="price_do">
</label></span>
<label>
<select name="sort" onchange="this.form.submit()">
<option value=""> </option>
<option value="ASC">По цене (сначала дешевые)</option>
<option value="DESC">По цене (сначала дорогие)</option>
</select>
<button type="submit">Отфильтровать</button>
</form>
<?php if ($_GET && !empty($_GET)) {
my_filter();
} ?>
function my_filter() {
$args = array();
$args[‘meta_query’] = array(‘relation’ => ‘AND’);
global $wp_query;
if ($_GET[‘price_ot’] != » || $_GET[‘price_do’] != ») {
if ($_GET[‘price_ot’] == ») $_GET[‘price_ot’] = 0;
if ($_GET[‘price_do’] == ») $_GET[‘price_do’] = 9999999;
$args[‘meta_query’][] = array(
‘key’ => ‘price’,
‘value’ => array( (int)$_GET[‘price_ot’], (int)$_GET[‘price_do’] ),
‘type’ => ‘numeric’,
‘compare’ => ‘BETWEEN’
);
}
if ($_GET[‘sort’] != ») {
$args = array(
‘meta_key’ => ‘price’,
‘orderby’ => ‘meta_value_num’,
‘order’ => $_GET[‘sort’]
);
}
query_posts(array_merge($args,$wp_query->query));
die();
}
add_action('wp_ajax_myfilter', 'my_filter');
add_action('wp_ajax_nopriv_myfilter', 'my_filter');
jQuery(function($){
$('.filter').submit(function(){
var filter = $(this);
$.ajax({
url:ajaxurl,
data:filter.serialize(),
type:filter.attr('method'),
beforeSend:function(xhr){
filter.find('button').text('Отфильтровать');
},
success:function(data){
filter.find('button').text('Отфильтровать');
$('#response').html(data);
}
});
return false;
});
});
Answer the question
In order to leave comments, you need to log in
You should read the documentation. Here, for example , there is also a video.
In short, the algorithm is as
follows 1. First, we cut wp_localize_script () with the necessary data. It is enough to pass a link and a nonce
2. We write a function for receiving and sending data and hang it with the wp_ajax_ hook
3. We catch the data from the form by clicking or switching and send it with Ajax. If the answer is positive, we display the result
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question