在做了一些广泛的研究之后,我用尽了所有的选择,决定在这里提出一个问题。我试图使用WP\\u Query和tax\\u Query参数通过AJAX获得一组经过过滤的帖子。
我目前有一个自定义的帖子类型叫做“词汇术语”,还有两个自定义的分类法叫做“词汇类别”和“难度级别”。从本质上说,我希望用户做的是选择一个类别,然后选择一个难度级别,然后加载任何标记了每个类别的帖子。下面是我的php函数和js。似乎我可以通过词汇术语进行筛选,但第二次尝试将任何内容传递到tax\\u查询时,它失败了。
有什么想法吗?
ajax游戏功能。php
function get_game_difficulty() {
// Nonce check
$nonce = $_REQUEST[\'nonce\'];
if (!wp_verify_nonce($nonce, \'ajax_scripts_nonce\')) die(__(\'Busted.\'));
global $wpdb;
global $wp_query;
global $post;
global $terms;
$html = "";
$success = false;
$gameCategory = $_REQUEST[\'gameCategory\'];
$gameDifficulty = $_REQUEST[\'gameDifficulty\'];
$html .= \'<h2>Listen and repeat each word you hear until you feel comfortable pronouncing each word.</h2>\';
$html .= $gameCategory;
$html .= $gameDifficulty;
$html .= \'<ul>\';
$args = array(
\'numberposts\' => 5,
\'post_type\' => \'vocabulary_terms\',
\'tax_query\' => array(
array(
\'taxonomy\' => \'vocabulary_categories\',
\'field\' => \'slug\',
\'terms\' => $gameCategory
)
)
);
$myposts = get_posts( $args );
foreach( $myposts as $post ) : setup_postdata($post);
$title = get_the_title();
$html .= \'<li>\'.$title.\'</li>\';
endforeach;
$html .= \'</ul>\';
// Build the response...
$success = true;
$response = json_encode(array(
\'success\' => $success,
\'html\' => $html
));
// Construct and send the response
header("content-type: application/json");
echo $response;
exit;
}
add_action(\'wp_ajax_nopriv_get_game_difficulty\', \'get_game_difficulty\' );
add_action(\'wp_ajax_get_game_difficulty\', \'get_game_difficulty\' );
ajax游戏脚本。js
$(document).on(\'click\', \'#vocabulary-games a.difficulty-level\', function() {
//$(\'#vocabulary-games a.difficulty-level\').click(function(){
// Store category slug in variable
var vocab_difficulty = $(this).attr(\'data-difficulty\');
var vocab_cat = $(this).attr(\'data-category\');
// post data to function
$.post(ajax_scripts.ajaxurl, {
dataType: "jsonp",
action: \'get_game_difficulty\',
nonce: ajax_scripts.nonce,
gameDifficulty: vocab_difficulty,
gameCategory: vocab_cat
}, function(response) {
if (response.success===true) {
$(\'#vocabulary-games\').children().fadeOut(\'slow\',function(){
//$(\'#vocabulary-categories\').children().hide(1,function(){
$(\'#vocabulary-games\').append().html(response.html);
//});
});
} else {
alert(\'!\');
// Bad Response message
}
});
}); // end click
最合适的回答,由SO网友:figureone 整理而成
您的代码看起来不错,但失败了,因为您的自定义分类法没有在AJAX调用的操作挂钩中注册。
我猜您正在根据Taxonomies documentation, 它告诉您将其添加到“init”操作挂钩。但是,在AJAX调用期间不会调用“init”。它仅在典型的页面请求或管理页面请求期间调用(请参阅Action Reference documentation). (注意:codex中的操作参考文档似乎已经过时了,它没有包括AJAX请求期间运行的任何操作列表。)
解决方法:如果需要访问自定义分类法,请在ajax函数的开头手动运行init操作,如下所示:
function get_game_difficulty() {
do_action("init");
// Code that relies on custom taxonomies being registered can be used below.
...
}
add_action(\'wp_ajax_nopriv_get_game_difficulty\', \'get_game_difficulty\' );
add_action(\'wp_ajax_get_game_difficulty\', \'get_game_difficulty\' );