AJAX has begun to dominate the web development world due to its many attractive features. It can handle database operations and fetch and display requested information without refreshing the entire webpage. In this article, you’ll learn how to make your WordPress plugin responsive by using AJAX.
This dynamic web development technique displays content at lightening fast speed. It’s speed makes AJAX a popular choice for website functions, such as:
- Posting comments,
- Uploading pictures,
- Liking posts, etc.
You can even take it a step further by developing your entire website through AJAX. Given its popularity, it should come as no surprise that the biggest CMS platforms include AJAX in their architecture. WordPress is one such CMS platform.
Since AJAX is accessible, experts recommend that you write your WordPress plugins in this language. Considering this, we will teach you how to create responsive plugins using AJAX.
Incorporating Scripts and Files
Let’s look at this stepwise:
1 Create a Foundation
Firstly, create a foundation. To build your AJAX plugin, you need to create the right environment. You can do this by adding the necessary scripts to help it function. Secondly, create an ajaxloadpost1 directory in your WordPress installation of the plugin directory.
In the same section, create ajaxloadpost1.php in your plugin’s header. In addition, by doing this, you will be able to activate your plugin from the plugin list.
Follow this step by adding the following code within your ajaxloadpost1.php:
- define(‘AJAXLOADPOSTURL’, WP_PLUGIN_URL.”/”.dirname( plugin_basename( __FILE__ ) ) );
- function ajaxloadpost1_enqueuescripts() {
- wp_enqueue_script(‘ajaxloadpost1′, AJAXLOADPOSTURL.’/js/ajaxloadpost.js’, array(‘jquery’));
- wp_localize_script( ‘ajaxloadpost1’, ‘ajaxloadpostajax’, array( ‘ajaxurl’ => admin_url( ‘admin-ajax.php’ ) ) );
- }
- add_action(‘wp_enqueue_scripts’, ajaxloadpost1_enqueuescripts);
2. Define the AJAX Load Post URL Variable
Next, you need to define the AJAX load post URL variable as it will be handy while pointing towards your plugin’s URL.
3. Add AJAX Load Post _ EnqueueScripts
After this, move onto adding ajaxloadpost_enqueuescripts to the WordPress’ wp_enqueue_scripts. Performing this action will help you enqueue all the scripts.
Your next step should be adding the JavaScript file ajaxloadpost.js. You can find it in the \wp-content\plugins\ajaxloadpost1\js\folder.
4. Create a JS Folder: WordPress Plugin Responsive Using AJAX
Now, create a JS folder and place your ajaxloadpost.js file inside it. As a result, do not worry about the proper sequence. WordPress will enqueue the files/scripts for you.
5. Add the JS Variable
Once you have created the JS folder, you can add the JS variables with wp_localize_script.
Incorporating AJAX Handler
Now, it is time to insert the AJAX handler whose function would be to create WordPress’ AJAX call. To perform this step, follow this set of code:
Now, it is time to insert the AJAX handler whose function would be to create WordPress’ AJAX call. To perform this step, follow this set of code:
- function ajaxloadpost_ajaxhandlers() {
- if ( !wp_verify_nonce( $_POST[‘nonce’], “ajaxloadpost_nonce”)) {
- exit(“Wrong nonce”);
- }
- $theseresults = ”;
- $content_posted = get_post($_POST[‘postid’]);
- $theseresults = $content_posted->post_content;
- die($theseresults);
- }
- add_action( ‘wp_ajax_nopriv_ajaxloadpost_ajaxhandlers’, ‘ajaxloadpost_ajaxhandlers’ );
- add_action( ‘wp_ajax_ajaxloadpost_ajaxhandlers’, ‘ajaxloadpost_ajaxhandlers’ )
The above-given code sequence will achieve two outcomes:
- Firstly, it will create a post ID of the post in question and,
- Secondly, it will create nonce.
Through this code sequence, you will be able to check the post ID and the nonce for their usefulness. Once you have completed the check, the codes will fetch the posts from $_POST variables.
Subsequently, you will be able to access any post and its content by utilizing the API get_post. In WordPress, you can get access through the post ID.
Once the AJAX handler functionality is in place, you can register the action in WordPress. In this way, the database can fetch appropriate data when you make an AJAX request.
Thus, to achieve this, you need to add your functions in the following manner:
- add_action( ‘wp_ajax_nopriv_ajaxloadpost_ajaxhandlers’, ‘ajaxloadpost_ajaxhandlers’ );
- add_action( ‘wp_ajax_ajaxloadpost_ajaxhandlers’, ‘ajaxloadpost_ajaxhandlers’ );
By the end of this step, you have registered all the right action in the admin-ajax-php URL. In addition, you will be able to make AJAX request to WordPress with ease.
AJAX and the Required JavaScript
Now, write the JS codes that will help AJAX in fetching appropriate data through AJAX handler. So, tThe code will be something like this to make WordPress plugin responsive using AJAX:
Function ajaxloadpost_loadpost(postid,nonce) {
jQuery.ajax({
type: 'POST',
url: ajaxloadpostajax1.ajaxurl,
data: {
action: 'ajaxloadpost_ajaxhandlers',
postid: postid,
nonce: nonce
},
success: function(data, textStatus, XMLHttpRequest) {
var loadpostresult = '#loadpostresult';
jQuery(loadpresult).html('');
jQuery(loadpresult).append(data);
},
error: function(MLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
This code achieves two inputs, i.e., nonce and the post ID. Then, we will create an AJAX call to the servers by utilizing the jQuery.ajax function. So, the URL will be the same as the AJAX URL of WordPress’s admin-ajax.php.
Moreover, you can find the required URL in the JavaScript variable. If you remember, we stored it there while enqueuing the required scripts.
Follow this step by specifying the action with the action handler’s name. We obtained the action handler’s name while registering with WordPress. You will also need to post the nonce along with the post ID.
If you are able to achieve it without any errors, you can move on to updating the id #loadpostresult <div>. This will fetch the appropriate content through our AJAX handler.
Putting the List of Posts on Display: WordPress Plugin Responsive Using AJAX
If you have reached up to this point without any errors. So, you can move on to displaying the post titles. To display posts. Finally, you need to input relevant codes to fetch the requested content through the AJAX call.
Following are the series of codes you will need to perform this step:
function ajaxloadpost_show_posts($thenumber = '5'){
$ourresults ='';
$query = new WP_Query( 'posts_per_page='.$ thenumber);
while ( $query->have_posts() ) :
$query->the_post();
$nonce = wp_create_nonce("ajaxloadpost_nonce");
$args = get_the_ID().",'".$nonce."'";
$thelink = ' <a onclick="ajaxloadpost_loadpost('.$args.');">'. get_the_title().'</a>';
$ourresults.= '<li>' . $thelink . '</li>';
endwhile;
wp_reset_postdata();
$ourresults.= '<div id="loadpresult"></div>';
return $ourresults;
}
function ajaxloadpost_sc_function( $atts ){
return ajaxloadpost_show_posts();
}
add_shortcode( 'AJAXLOADPOST', 'ajaxloadpost_sc_function' );
In the first set of code, ajaxloadpost_show_posts, you can submit a query to fetch the latest post. So, you can then loop over the latest post’s list and integrate the names of the titles through the <a> tag.
It will signal the JavaScript ajaxloadpost_loadpost to fetch the post ID and the nonce. Moreover, this action will create an empty <a>. The AJAX handler’s results will fill this empty <a>.
Furthermore, you can also create a shortcode for every webpage. To achieve this, you can add [AJAXLOADPOST] on the page to see a list of the titles. Once done, your web page will contain a list of the latest posts’ titles.
Takeaway – Make Your WordPress Plugin Responsive Using AJAX in a Few Simple Steps
As you can see from this plugin tutorial. In addition, AJAX is not difficult to use. You can incorporate it into WordPress with ease. It makes WordPress web development a lot easier than before.
If you are new to this, AJAX may sound a bit complicated. However, once you understand it, it looks and works great!
You can add any AJAX plugin to your WordPress site using the steps given above. Whether it’s an AJAX page loader or a third-party plugin like an event calendar.
With these steps, users can click and view posts without having to load the entire webpage. So, If you like, you can customize the code set by including more features in it.
Finally, we hope this tutorial is clear and simple enough for you to understand and practice.