How to use AJAX precisely in WordPress Custom Themes?

Parth Shah
Techcompose
Published in
2 min readOct 5, 2018

AJAX is a combination of HTML, CSS and JavaScript code that enables you to send data to a script and then receive and process the script’s response without needing to reload the page. Basically, AJAX is not a programming language, but if you want to use AJAX, you have to familiar with JavaScript/JQuery, HTML, CSS, and PHP.

How to use AJAX with WordPress?

AJAX is already used in WordPress backed so in a wp-admin folder there is already admin-ajax.php file is placed. Every AJAX requests pass through the admin-ajax.php file. The request you are passing through GET or POST method is called as an action. On the bases of action admin-ajax. PHP file creates two hooks called wp_ajax_my_action and wp_ajax_nopriv_my_action, my_action is the value of the GET or POST variable action.

Difference between wp_ajax_ and wp_ajax_nopriv_

wp_ajax_ is fired for users who are logged-in, while wp_ajax_nopriv_ is fired while the user is not logged-in. You can use both hooks for your function, but here you should note that hook will be fired once in a single request.

So, here is the basic example that load posts using AJAX

Step 1: Create a template file and put below code into your file.

Here, input type hidden is used for fetching the total number of pages, while div id more_posts is used for display next posts by clicking on it.

Step 2: Localize your script into functions.php

Step 3: Add function that load posts into functions.php file.

Step 4: Place your AJAX JS into ajax.js file.

Conclusion:

This is a quick tutorial for AJAX, there is a lot of methods and functionalities you can add. This article helps to how you can implement AJAX into your website.

Four points you should keep in mind while you use AJAX:

1. Create a template file for your logic.

2. Create a callback function for calling AJAX.

3. Localize scripts in function.php

4. Make the AJAX call.

It is very necessary to choose WordPress Development Company for a quality WordPress website development that not only provide you a new enhance design but also SEO friendly build up to make sure you will get a good visibility across various Search Engines. Contact us to discuss your website Project or Hire Dedicated Wordpress Developer. You can reach us at sales@techcompose.com

--

--