AJAX In WordPress (2020 Edition)
AJAX is extremely commonplace in websites today, but do you know how to use it in WordPress? Let’s take a look at how AJAX works in WordPress and how to navigate the way AJAX is used within WordPress.
WordPress in AJAX – Theory
AJAX is fairly simple. You use JavaScript to make a request to a resource ‘behind the scenes’ and receive a response without the need for the page the visitor is currently viewing to be fully refreshed.
How is AJAX in WordPress so different? WordPress changes things in 2 ways: We should pass along a security token (nonce), and we need to pass along an ‘action’ to inform WordPress what function to run to provide the response.
Important!
This is a look at how each component of AJAX works in WordPress. How it is used may differ depending on what your goal is. Please keep that in mind.
WordPress in AJAX – Example
Let’s take a look at a simple, and as always, mostly pointless example. First let’s make our response function, this will be done using PHP. It can be placed anywhere that makes sense for your needs, but let us assume this is for a theme and will be placed in functions.php
to keep things simple.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
add_action('wp_ajax_check_meta_value', 'ajaxexample_check_meta_value'); add_action('wp_ajax_nopriv_check_meta_value', 'ajaxexample_check_meta_value'); function ajaxexample_check_meta_value() { check_ajax_referer('check-meta-value'); $post_id = intval($_POST['id']); $value = get_post_meta($post_id, 'value_to_check', true); if($value) { echo json_encode([ 'success' => true ]); wp_die(); } echo json_encode([ 'success' => false ]); wp_die(); } |
To keep things brief this code is very simple. It simply checks a post meta value and returns a truthy JSON response if it exists, or a falsy one if it does not.
Remember!
You must always remember to wp_die()
when your code output should end in any AJAX response functions. Using wp_die()
instead of die()
gives better integration with WP for debugging.
Note the two actions. wp_ajax
is for authenticated users. wp_ajax_nopriv
is for non-authenticated users. Remember this when testing. If you constantly receive a 0
response check your authentication status matches the action you are using.
Important!
Please remember to sanitize any data that you do not know the source of, especially input from visitors. WP has built in santization functions so please use them.
JavaScript
Now. Let’s take a look at what the corresponding JavaScript might look like. We will be using jQuery here because it is commonly used with WordPress, but whatever you prefer will work just fine.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
(function($){ function check_meta_value() { $.post(ajaxExample['ajaxUrl'], { _ajax_nonce: ajaxExample['nonce'], action: 'check_meta_value', id: '123' }, function(response) { if(response['success'] === true) { alert('It was true!'); } else { alert('It was false!'); } }, "json"); } $('#my_button').on('click', check_meta_value); })(jQuery) |
We will save this in a file called ajaxexample.js
. In reality you’d likely place this in your theme or plugin JS file.
Continuing our ‘not very helpful’ example we have a simple POST request triggered by clicking a button. We pass along our needed data:
action
, this is the name you added after wp_ajax
or wp_ajax_nopriv
in your action on the PHP side of things. It can be anything you like as long as they match each other.
id
, this is not required. It is just for out example. Here it would always return the same result, in reality you’d probably grab this from somewhere via JS or it might be a value entered by the visitor.
_ajax_nonce
, this is a special key that WordPress automatically checks for when using check_ajax_referer
on the PHP side. You can customize it using the second parameter of check_ajax_referer
but I like to use the default.
Now. You may be wondering where on earth does ajaxExample
come from? Well we need to add that. We will do that using wp_localize_script
to pass some needed data from the PHP side along with enqueuing our JS above.
1 2 3 4 5 6 7 8 |
add_action('wp_enqueue_scripts', 'ajaxexample_enqueue_scripts'); function ajaxexample_enqueue_scripts() { wp_enqueue_script('ajax-example', get_stylesheet_directory_uri() . '/js/ajaxexample.js', [ 'jquery' ], '1.0', true); wp_localize_script('ajax-example', 'ajaxExample', [ 'ajaxUrl' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('check-meta-value'), ]); } |
Here we enqueue our script, but also use wp_localize_script
to add some needed JS variables to the page that our previous code can use.
Heads up!
It should be noted that you should probably use wp_add_inline_script()
since WordPress 4.5 instead of wp_localize_script()
however in reality a lot of us still use the latter, even in professional settings (even if we shouldn’t).
Troubleshooting
That’s pretty much it. AJAX in WordPress can feel a little ‘long-winded’, but you get used to it. Here are some answers to some common issues.
Numbers in Output
If you get a 0
response your action names may not match, or you may be authenticated when using an non-authenticated action (or vice versa).
if you get a -1
response then your nonce is probably failing to be verified. Check the names used for checking and generation both match.
WP JSON API
WordPress has a JSON API built into every website. I would advise using this if your end goal is to just grab some post data or anything that may already be available via that.
That is a completely different tutorial though and would be pretty much completely done via JavaScript.
I hope this has helped as a ‘crash course’ on using AJAX in WordPress. The process has not really changed since my last posts on the subject, but after a couple of requests I figured it was time for a 2020 refresher.