1
我正在嘗試使用單選按鈕製作Ajax後置過濾器。以便用戶可以使用單選按鈕篩選多個類別。WordPress中的單選按鈕的Ajax後置過濾器
這是我所使用的代碼:
前端形式:
<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>
的script.js:
jQuery(document).ready(function($){
$('#filter .br').click(function(){
// Declaratie van array
var choices = {};
$('.contents').remove();
$('.filter-output').empty();
$('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);
$.ajax({
url: ajaxobject.ajaxurl,
type :'POST',
data : {
'action' : 'call_post', // Naam van de PHP functie
'choices' : choices,
},
success: function (result) {
$('.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);
}
});
})
});
的functions.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();
get_template_part('content');
endwhile;
wp_reset_query();
else :
wp_send_json($query->posts);
endif;
//}
die(); }
但我不斷收到以下錯誤:
script.js:20 Uncaught ReferenceError: ajaxobject is not defined
而且我不知道如何解決它。所以我希望有人能幫助我。我對AJAX的經驗很少,這就是爲什麼我要求幫助。
鏈接到網站: http://5.79.72.162/~delta/category/vacancies/
謝謝:),它需要連接到admin-ajax.php。現在只需要找出爲什麼在製作陣列時不顯示信息。 – Rachelle