AJAX in WordPress – A Step by Step Guide [With Example]
Introduction to AJAX
Benefits of using AJAX in WordPress Website
- AJAX is Fast – AJAX Response is Faster than typical Page Loading Approach.
- Better User Experience – User Don’t have to wait for the page to load as only the requested section refreshes.
Understanding the Basics of AJAX How it Works –
AJAX works in these 4 Steps
Step 1 – An AJAX request is sent to admin-ajax.php with the “action” parameter and other data.
Step 2 – The admin-ajax.php file looks for the action and the function linked to it in functions.php.
Step 3 – The function written in functions.php creates the output and sends it back as an AJAX response.
Step 4 – Response is received on the page and displayed as Output.
Step by Step Explanation of AJAX in WordPress.
The Page Template – A New page template to show trigger button and empty container for output.
The Jquery post method sends a post request on ajaxurl bound to the action my_ajax_action.
The function bound with the action runs the loop and sends the output in response.
The JS function Recieves the output & Displays it in console and the div with id postcontainer.
Basic Example of AJAX in WordPress
To implement ajax in WordPress, we need 2 things –
1. A page to trigger AJAX and Display the Output.
2. A PHP function to handle the backend process.
Create a Page Template
Go into the Active theme directory of Your WordPress website and create a file wordpress-ajax.php and insert the following code into it
Add WordPress Action in functions.php file
Now add the following code at the end of the functions.php file –
Similarly, we can create the Following –
1. Load More Posts in WordPress using AJAX
2. Filters Posts in WordPress using AJAX
3. Change Tab content in WordPress using AJAX
4. AJAX Pagination in WordPress
Simple AJAX Post Filters Example code in WordPress
Below is an example to make a simple AJAX filtered post Archive Page.
The code consists of 2 Parts-
1. Page Template – Paste in the existing page template or create a new file.
2. PHP Function – To be pasted in functions.php.
Requirements/Dependencies for Making AJAX Post filters in WordPress
WordPress – v5.8
PHP – v8
Post Categories – Add 3-4 Different Categories from Dashboard
Posts – Add a Minimum of 1 post in each Category.
Add the following code to Your Page template file.
Add the following code to Your functions.php file.