WordPress is an excellent platform for building websites; however, the content manager tool comes with its drawbacks. If you have built your website on WordPress, then it is not uncommon to face the slow load speed issue. Due to the large number of plugins added along with the influx of databases and codebases, it is actually not uncommon. However, it is important to focus on the solution. You don’t want your audience to get impatient and leave due to the slow speed and lose potential business!
What if we told you that you could optimize the speed of your WordPress website by integrating a simple feature into your plugins, known as AJAX. The term AJAX is short for Asynchronous JavaScript and XML. AJAX helps you to improve the speed of your website. It will only load a certain part of the page and keep the remaining page static, thereby improving the load time. Several plugins and apps are already using this feature to help improve the speed of their webpages even today.
In just a small amount of time, AJAX has gained an excellent reputation in the Digital Marketing world and it is being used by the majority of website owners. Luckily, WordPress provides excellent support for AJAX, making it easier to write plugins that are integrated into AJAX. With support from WordPress and our article, you should be able to integrate AJAX into your plugins in no time.
Below is a step-by-step guide to walk you through the process.
Step#1 – Create your Plugin
The first step is to create a simple plugin that you can then use to develop a more advanced product that is more responsive and reduces the loading time of your webpage. The good news is that you won’t have any difficulty in creating the plugin because all you need to do is create a file that includes one-liner data.
You can do this by searching the file “wp-content/plugins” and generate a folder of whatever name suits you. Once you have done this, you now need to open the folder and create a file with the name: “name_of_the_plugin.php”. Once you have opened this file in the text editor, type the following code in the text editor.
<?php
/*
Plugin Name: Your choice
Plugin URI: http://yout-choice.com
Description: This loads post via ajax
Author: Your name
Author URI: http://yourname.com
Version: 1
*/
Step #2 – Add the JavaScript Library
You start this step by creating an “ajaxloadpost” directory. How to do so? It’s pretty simple since you can install it along with the WordPress plugin. Once this step is complete you can now create the plugin that you have coded and run it. You then need to add the code below into your ajaxloadpost:
define('AJAXLOADPOSTURL', WP_PLUGIN_URL."/".dirname( plugin_basename( __FILE__ ) ) );
function ajaxloadpost_enqueuescripts() {
wp_enqueue_script('ajaxloadpost', AJAXLOADPOSTURL.'/js/ajaxloadpost.js', array('jquery'));
wp_localize_script( 'ajaxloadpost', 'ajaxloadpostajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
add_action('wp_enqueue_scripts', ajaxloadpost_enqueuescripts);
You must direct WordPress through the URL of the plugin created; this why you need to define the variable by the name of AJAXLOADPOSTURL.
AJAX is always used with a combination of programming languages, we will be working with JavaScript in our remaining article. Look for ajaxloadpost.js in the \wp-content\plugins\ajaxloadpost\js\folder and add JavaScript to it. You can now add the JavaScript variable to your script.
Step #3 – Integrating the AJAX Handler
Once all of the above is sorted, you can finally move on to integrating the AJAX handler into your plugin. The following is the code for your AJAX handler:
function ajaxloadpost_ajaxhandler() {
if ( !wp_verify_nonce( $_POST['nonce'], "ajaxloadpost_nonce")) {
exit("Wrong nonce");
}
$results = '';
$content_post = get_post($_POST['postid']);
$results = $content_post->post_content;
die($results);
}
The code above will basically be fulfilling two tasks. It will first develop an ID for the posts required by the user. The second task is to create “nonce”. You don’t have to worry about the second element for the time being (It has been described in detail at the end of the article).
Instead, you should be moving on to the second step which is to get your AJAX handler registered within the WordPress directory. This will enable the AJAX function to be called once requested. This action can be achieved through the code mentioned below:
add_action( 'wp_ajax_nopriv_ajaxloadpost_ajaxhandler', 'ajaxloadpost_ajaxhandler' );
add_action( 'wp_ajax_ajaxloadpost_ajaxhandler', 'ajaxloadpost_ajaxhandler' );
Having background knowledge about JavaScript is a huge plus for you, if you not adept to this programming language take help from an expert to guide you through the entire process. You can also polish your JavaScript skills through a web tutor or by reading articles here.
Step #4 – Using JavaScript for AJAX
The next thing you need is to write a function that will enable AJAX to call and update data that has been returned through the AJAX handler. The function is generally ajacloadpost.js. The following code can be used to determine the action described above.
function ajaxloadpost_loadpost(postid,nonce) {
jQuery.ajax({
type: 'POST',
url: ajaxloadpostajax.ajaxurl,
data: {
action: 'ajaxloadpost_ajaxhandler',
postid: postid,
nonce: nonce
},
success: function(data, textStatus, XMLHttpRequest) {
var loadpostresult = '#loadpostresult';
jQuery(loadpostresult).html('');
jQuery(loadpostresult).append(data);
},
error: function(MLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
The function above will take two inputs, one of them is the id of the post and the second one is nonce. You may use the jQuery.ajax function to make the call to the server. Once successful, update the <div> of id #loadpostresult with the data that was returned through the AJAX handler. The last bit of the code is a condition in case of an error. If an error occurs the system is alerted with a pop-up.
Step #5 – Displaying the lists
Once all the functions have been sorted you can move towards the last step which is to display the post title. Do keep in mind that each click might be towards a different post title and your code should be able to fetch the code that has been called. The following code can help you achieve this:
function ajaxloadpost_show_latest_posts($number = '5'){
$results ='';
$the_query = new WP_Query( 'posts_per_page='.$number );
while ( $the_query->have_posts() ) :
$the_query->the_post();
$nonce = wp_create_nonce("ajaxloadpost_nonce");
$arguments = get_the_ID().",'".$nonce."'";
$link = ' <a onclick="ajaxloadpost_loadpost('.$arguments.');">'. get_the_title().'</a>';
$result.= '<li>' . $link . '</li>';
endwhile;
wp_reset_postdata();
$result.= '<div id="loadpostresult"></div>';
return $result;
}
function ajaxloadpost_shortcode_function( $atts ){
return ajaxloadpost_show_latest_posts();
}
add_shortcode( 'AJAXLOADPOST', 'ajaxloadpost_shortcode_function' );
What is “nonce”?
A nonce is used to check whether the request is coming from an authentic source or not. A nonce can be generated using a simple WordPress function: “wp_create_nonce”. It can be further checked through an AJAX handler using the function: “wp_verify_nonce”. Using this feature is extremely important if you are doing a sensitive task on your WordPress.
Conclusion
Integrating AJAX with your plugins can help improve the responsiveness of your pages visibly. If you are not comfortable with JavaScript, you may opt for a programming language that you find easier to code with or find an expert who can help you code for your plugin. Try to integrate AJAX into your plugins and you won’t be disappointed!