Step 1: Create your javascript file
To use ajax, you’ll probably use a javascript file. Create it. Let’s name it my-custom-ajax-javascript-file.js. Let’s create a folder js in the theme root and place it there.
Step 2: Enable the WordPress Ajax handler
As part of its core, WordPress includes a handler file called “admin-ajax.php” to facilitate all things AJAX. This file will allow you to use jQuery to call PHP functions much like an API.
To utilize admin-ajax.php you need to instantiate it using WordPress’ wp_localize_script() function. The best place to do this is in your theme’s functions.php file.
$ajax_data = array( 'ajaxurl' => admin_url('admin-ajax.php') ); wp_enqueue_script('custom_ajax', get_template_directory_uri() . '/js/my-custom-ajax-javascript-file.js', array(), null, true); wp_localize_script('custom_ajax', 'ajax_data', $ajax_data);
Step 3: Create your PHP functions
Next you’ll want to create some PHP functions you can invoke within your AJAX call. For example:
function my_ajax_function() { die(); }
Notice that you’ll have to add the die() function at the end of the PHP function, because without this function, admin-ajax.php will append the value outputted with a “0”—obviously not something you want.
For each PHP function you create, you’ll want to declare it in functions.php using WP’s add_action() hook. This ensures you can call the functions via AJAX when you want to use them.
If you want to make the function available regardless of login state or in the WP admin, add the following:
add_action("wp_ajax_nopriv_my_ajax_function", "my_ajax_function"); // make the function available for not logged-in users add_action("wp_ajax_my_ajax_function", "my_ajax_function"); // make the function available for logged-in users
Step 4: Call your PHP functions using jQuery
If your PHP function is expecting additional request variables, you’ll also want to pass these in the data: line separated by commas.
More coming soon…