最合适的回答,由SO网友:Adam Mo. 整理而成
要使用ajax,您必须钩住此函数,因此您的函数如下所示:
function write_cat_list($cat){
$cats = get_categories(\'hide_empty=0\');
if($cats) :
$tinyMCE_list = array();
foreach ($cats as $cat) :
$tinyMCE_list[] = array( \'text\' => $cat->name , \'value\' => $cat->term_id );
//write_cat_list($cat->term_id);
endforeach;
$jscode = json_encode($tinyMCE_list); //to convert from array to opject
echo $jscode;
endif;
die();
}
add_action( \'wp_ajax_cat_list\', \'write_cat_list\' );
和jquery:
jQuery.ajax({
type: \'post\',
url: ajaxurl,
data: {action : \'cat_list\'},
success: function(data){
console.log(data);
// use var data
}
});
您还可以使用
localize
要使用它而不是ajax,请删除
die();
并添加以下内容:
wp_enqueue_script( \'your js file handel\' );
wp_localize_script( \'your js file handel\', \'jscode\',array( \'cat_list\' => $jscode));
以及
add_action
替换为:
add_action( \'wp_enqueue_scripts\', \'write_cat_list\' );
和jquery:
console.log(jscode.cat_list);
the full code for ajax:
// php
function write_cat_list($cat){
$cats = get_categories(\'hide_empty=0\');
if($cats) :
$tinyMCE_list = array();
foreach ($cats as $cat) :
$tinyMCE_list[] = array( \'text\' => $cat->name , \'value\' => $cat->term_id );
//write_cat_list($cat->term_id);
endforeach;
$jscode = json_encode($tinyMCE_list); //to convert from array to opject
echo $jscode;
endif;
die();
}
add_action( \'wp_ajax_cat_list\', \'write_cat_list\' );
// jquery
jQuery.ajax({
type: \'post\',
url: ajaxurl,
data: {action : \'cat_list\'},
success: function(data){
console.log(data);
// use var data
}
});
the full code for localize:
// php
function write_cat_list($cat){
$cats = get_categories(\'hide_empty=0\');
if($cats) :
$tinyMCE_list = array();
foreach ($cats as $cat) :
$tinyMCE_list[] = array( \'text\' => $cat->name , \'value\' => $cat->term_id );
//write_cat_list($cat->term_id);
endforeach;
$jscode = json_encode($tinyMCE_list); //to convert from array to opject
echo $jscode;
endif;
wp_enqueue_script( \'your js file handel\' );
wp_localize_script( \'your js file handel\', \'jscode\',array( \'cat_list\' => $jscode));
}
add_action( \'wp_enqueue_scripts\', \'write_cat_list\' );
// jquery
console.log(jscode.cat_list); // jscode.cat_list var handel the object