xoomer xoomer - 4 months ago 87
Ajax Question

Wordpress when logged in as admin AJAX call returns 0

When using WordPress as admin & calling a WordPress function with AJAX I get "0". But when logged out as admin, everything is working fine.

Maybe anyone has gotten similar issues like mine and knows a possible fix?

I want that both logged in as admin, and logged out, would return the output (not 0 of course).

This is the function in functions.php file.

add_action('wp_ajax_nopriv_get_category_data', 'getCategoryData');
add_action('wp_ajax_load_get_category_data', 'getCategoryData');

function getCategoryData()
$data = [
'category' => htmlspecialchars($_POST['category'])

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args= array(
'post_type' => 'Coupons',
'posts_per_page' => 8,
'post_status' => 'publish',
'paged' => $paged,
'rewrite' => array( 'slug' => 'CustomCat' ),
'caller_get_posts'=> 1

$couponBlock = new WP_Query( $args );

if ($data['category']) {
$the_query = new WP_Query(array ('cat' => $data['category'], 'posts_per_page' => 8) );
if ($the_query->have_posts()):
while ($the_query->have_posts()): $the_query->the_post();
get_template_part('template/ajaxCustomCat', 'page');

} else {
return 'no data';


You have to register the ajax function as an admin or privileged ajax call as well. So your call should look like this:

add_action( 'wp_ajax_add_foobar', 'prefix_ajax_add_foobar' );
add_action( 'wp_ajax_nopriv_add_foobar', 'prefix_ajax_add_foobar' ); 


Remember that you're also returning data via ajax so a return for AJAX to read is actually an echo. So data that needs to be sent back to the frontend should be echoed out. If you want to remove the 0 that wordpress sends along with its output, add an exit() at the end of your function to signal a finished call.