To ajax this function you have hook it, so your function will be like this :
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' );
and the jquery:
jQuery.ajax({
type: 'post',
url: ajaxurl,
data: {action : 'cat_list'},
success: function(data){
console.log(data);
// use var data
}
});
also you can use localize
instead of ajax
to use it remove die();
from your function and add this:
wp_enqueue_script( 'your js file handel' );
wp_localize_script( 'your js file handel', 'jscode',array( 'cat_list' => $jscode));
and add_action
replace it with :
add_action( 'wp_enqueue_scripts', 'write_cat_list' );
and the 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