大家好,我在使用Ajax过滤自定义帖子类型“资源”时遇到问题。我试图通过两种分类法过滤帖子,然后在提交按钮上的单击事件上激活Ajax调用。我不断收到“0”响应,但不确定我遗漏了什么。如果有人能帮助我,我将不胜感激!干杯,桑尼
以下是我的jQuery:
function filterResources(){
var the_topic_filter = $(\'#the_topic_selecter\').val();
var the_resourcetype_filter = $(\'#the_resourcetype_selecter\').val();
$(\'#results\').html(\'\');
$(\'#results\').html(\'<tr><td colspan="5" class="thinking"><img src="/wp-content/themes/limenetwork/images/ajax-spinner.gif" /></td></tr>\');
// AJAX CALL
var data = {
action: \'resourcehub_filter\',
send_the_topic_filter : the_topic_filter,
send_the_resourcetype_filter : the_resourcetype_filter,
};
// RESPONSE
jQuery.post(ajaxurl, data, function(response) {
$(\'#results\').html(\'\');
$(\'#results\').html(response);
if(!$.trim(response)){
$(\'#results\').html(\'<tr><td colspan="5" class="thinking">We could not find any resources, please try again.</td></tr>\');
}
});
}
这是我的功能。php
// RESOURCE HUB FILTER
add_action( \'wp_ajax_resourcehub_filter\', \'resourcehub_filters\' );
add_action( \'wp_ajax_nopriv_resourcehub_filter\', \'resourcehub_filter\' );
function resourcehub_filter() {
// GET VARS
$the_topic_filter = $_POST[\'send_the_topic_filter\'];
$the_resourcetype_filter = $_POST[\'send_the_resourcetype_filter\'];
// LOOP ALL RESOURCES (filter)
global $post;
// FOR NO FILTERS SELECTED
if( $the_topic_filter == "" && $the_resourcetype_filter == ""){
$args = array(
\'post_type\' => \'resource\',
\'post_status\' => \'publish\',
\'posts_per_page\' => 10,
\'orderby\' => \'date\',
\'order\' => \'DESC\',
);
} else {
$args = array(
\'post_type\' => \'resource\',
\'post_status\' => \'publish\',
\'posts_per_page\' => -1,
\'orderby\' => \'date\',
\'order\' => \'DESC\',
\'tax_query\' => array(
\'relation\' => \'OR\',
array(
\'taxonomy\' => \'topic_tax\',
\'field\' => \'slug\',
\'terms\' => array( $the_topic_filter )
),
array(
\'taxonomy\' => \'resource_tax\',
\'field\' => \'slug\',
\'terms\' => array( $the_resourcetype_filter )
),
),
);
}
$myposts = get_posts( $args );
foreach ($myposts as $post) : start_wp(); ?>
<tr>
<td><a href="<?php the_field(\'link\'); ?>"><?php the_title(); ?></a></td>
<td><?php the_title(); ?></td>
<td>
<!-- GET ACF TAXONOMY -->
<?php
$terms = get_field(\'topic\');
if( $terms ):
foreach( $terms as $term ):
echo $term->name; echo \' \';
endforeach;
endif; ?>
</td>
<td><span class="new badge" data-badge-caption="
<?php
$terms = get_field(\'resourcetype\');
if( $terms ):
foreach( $terms as $term ):
echo $term->name;
endforeach;
endif;
?>
"></span></td>
</tr>
<?php endforeach;
rewind_posts();
wp_die();
}
我添加了如下Ajax:
// ADD AJAX TO WORDPRESS HEADER
add_action( \'wp_head\', \'my_ajaxurl\' );
function my_ajaxurl() {
$html = \'<script type="text/javascript">\';
$html .= \'var ajaxurl = "\' . admin_url( \'admin-ajax.php\' ) . \'"\';
$html .= \'</script>\';
echo $html;
}