Basic WordPress AJAX Call

WordPress AJAX uses actions to connect your jQuery action with a traditional WordPress action. Take a look at the example WordPress provides in their docs. There’s 2 hooks:

add_action( "wp_ajax_{$jquery_action_string}", "callback_function_name" );

The above will only work for authenticated ( logged in ) users. For non-logged-in users we use nopriv:

add_action( "wp_ajax_nopriv_{$jquery_action_string}", "callback_function_name" );

So in our case we would use both:

function return_fruits() {
    echo json_encode( ['fruits' => ['apples', 'pears']]);
    exit();
}
add_action( 'wp_ajax_getFruits', 'return_fruits' );
add_action( 'wp_ajax_nopriv_getFruits', 'return_fruits' );

Note, I changed your call back function name to identify that the ajax action and the callback name do not need to be identical. Also note, you would want to echo this data instead of return it.

Leave a Comment