Today, I’m going to show you how to use Ajax in WordPress with an easy example step by step.
In our example, it uses Ajax to get post title
from post id
in an input.
Step 1: Write a text input to enter post id
, a button that will be clicked to get post title
and a div
to show the result.
1 2 3 4 5 |
<div> <input type="text" name="txt_post_id" class="txt-post-id"> <input type="button" class="btn-get-post" value="Get post title"> <div class="result"></div> </div> |
Step 2: Create an Ajax function that gets post id
and sends post title
if it’s existed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
function get_post_title_by_id() { // This function will verify the AJAX request to prevent processing requests external of the blog. check_ajax_referer( 'get-post-title-by-id' ); // Check if post id is empty or equal zero then return error if ( empty( $_POST['post_id'] ) ) { wp_send_json_error(); } // Get post title by post id $post_title = get_the_title( $_POST['post_id'] ); // If post title is not null then return it if ( $post_title ) { wp_send_json_success( array( 'post_title' => $post_title, ) ); } wp_send_json_error(); } // Hook to WordPress Ajax to add our ajax function add_action( 'wp_ajax_get_post_title_by_id', 'get_post_title_by_id' ); // For non-logged in users, you must use the wp_ajax_nopriv_* action instead wp_ajax_. |
Step 3: Enqueue script and pass some variables to Javascript
1 2 3 4 5 6 7 8 9 10 11 12 |
function enqueue_scripts() { wp_enqueue_script( 'my-script', get_template_directory_uri() . '/js/my-script.js', array( 'jquery' ), '1.0' ); wp_localize_script( 'my-script', 'obj', array( 'ajaxUrl' => admin_url( 'admin-ajax.php' ), // Generates and returns a nonce // It's used to verify Ajax request. See at the first line of the function in step 2 'nonceName' => wp_create_nonce( 'get-post-title-by-id' ), ) ); } add_action( 'wp_enqueue_scripts', 'enqueue_scripts' ); |
Step 4: Create a jQuery script to catch click
event from the button and pass parameters to Ajax function and get the result.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
jQuery( function( $ ) { $( '.btn-get-post' ).on( 'click', function() { var $result = $( '.result' ); $.ajax( { type : 'post', dataType : 'json', url : obj.ajaxUrl, data : { action : 'get_post_title_by_id', post_id : $( '.txt-post-id' ).val(), _ajax_nonce : obj.nonceName, }, success: function( response ) { if( response.success ) { $result.html( response.data.post_title ); } else { $result.html( 'No post is found' ); } } } ); } ); } ); |
That’s all! Now we know how to use Ajax in WordPress.