AJAX in WordPress Themes
For some reason, it seems really hard to find a nice, simple, copy-and-paste-able resource for explaining how to do AJAX requests in WordPress themes the-right-way™. So here it is.
Backend
Let's add the function that will return the AJAX response from the backend. This is normally added to the theme functions.php file:
add_action( 'wp_ajax_my_ajax_method', 'my_ajax_method' );
add_action( 'wp_ajax_nopriv_my_ajax_method', 'my_ajax_method' );
function my_ajax_method() {
check_ajax_referer( 'my-nonce', 'nonce' );
// do something...
wp_send_json( [ 'success' => true ] );
}
Notes:
-
We need to add a second
noprivaction so that the request works for users who are not logged in. -
wp_send_jsontakes care of setting theContent-Type: application/jsonheader and also callswp_dieto prevent any further processing.
Frontend
First, we need to output some variables to use in our frontend Javascript. Again in the theme functions.php file:
wp_localize_script( 'my-handle', 'MyScript', [
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'my-nonce' ),
] );
Notes:
-
my-handleshould be the same as the handle for your enqueued script file. -
These variables will be made available as a global Javascript object with the given object name. For example,
MyScript.ajaxurl. -
ajaxurlis not defined for the frontend so we'll just add it here.
Finally, we can create the AJAX request on the frontend. Using jQuery, it will look something like this:
$.post( MyScript.ajaxurl, {
action: 'my_ajax_method',
nonce: MyScript.nonce,
} )
.done( function ( response ) {
// do something...
} )
.fail( function ( jqXHR, textStatus, error ) {
console.error( error );
} );