Making your WordPress Plugin Responsive by using AJAX

WordPress Plugin Responsive

AJAX is the latest development methodology and the one that is slowly gaining momentum due to the ease of use it provides to its developers. By simply integrating AJAX within your WordPress plugins, you are essentially reducing the need to constantly reload the entire webpage. In other words, AJAX will make your WordPress Plugin Responsive and enable users to get new information by reloading only that specific part while keeping the rest of the page static.

This not only makes the web pages or plugins responsive but also cuts down the wait time to half.  There are several plugins and applications that employ Ajax to create better experiences for users. For example, WooCommerce uses Ajax feature to improve Add to Cart behavior.

With the AJAX enabled option, your customers will be able to continue shopping even after adding a product to cart.

Considering its benefits, we will teach you how to make your WordPress plugins responsive through AJAX.

Creating a Plugin

Before you can work your magic with AJAX, you need to have a basic plugin foundation that you can use to create an advanced and responsive product.

Creating a plugin is not difficult as all you require is the creation of a file that contains one-liner content. For this purpose, first step is to navigate to the wp-content/plugins file and create a brand new folder with a name of your choice. Open the folder and create a new file name_of_the_plugin.php. Now, view the file in any text editor and write the following information:

<?php

/*

Plugin Name: Coolness Inducer

Plugin URI: http://coolness-inducer.com

description: >-

a plugin perfect for making your website extra cool.

Version: 1.3

Author: Ms. Vader

Author URI: http://msvader.com

License: GPL2

*/

?>

Before doing this, create an ajaxloadpost directory in your WordPress’ plugin installation. Once you do this, create the plugin and activate it. After this, include the following information within 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);

Then, define the AJAXLOADPOSTURL variable because you will need it to direct WordPress to the URL of your plugin. Now you have to enqueue your scripts which you can do by adding ajaxloadpost_enqueuescripts to wp_enqueue_scripts of the WordPress.

Keep in mind that AJAX can never be used in its raw form. It will always be used in combination with other programming languages, i.e. jQuery or JavaScript. In this case, we will work with JavaScript so you need to have some basic understanding of it.

Moving on, add JavaScript to the ajaxloadpost.js which you will find in the \wp-content\plugins\ajaxloadpost\js\folder. Follow this action by creating a JS folder and place the ajaxloadpost.js in it.

Now, use the WordPress wp_localize_script to add the required JS variable. This action will provide a structure to your directory and enqueue your scripts.

Writing AJAX Handler

To write the AJAX handler, you will need the following codes:

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);

}

add_action( ‘wp_ajax_nopriv_ajaxloadpost_ajaxhandler’, ‘ajaxloadpost_ajaxhandler’ );

add_action( ‘wp_ajax_ajaxloadpost_ajaxhandler’, ‘ajaxloadpost_ajaxhandler’ );

Completing this action will result in two outcomes. First, it will create the ID of the posts which the users require and second is that it will create nonce. But that is beside the point! Once the AJAX handler’s codes are in place, you need to move to the next step that is to register the AJAX handler in the WordPress directory. Doing this will make the WordPress plugin responsive to the AJAX calls. You can achieve this through these codes:

add_action( ‘wp_ajax_nopriv_ajaxloadpost_ajaxhandler’, ‘ajaxloadpost_ajaxhandler’ );

add_action( ‘wp_ajax_ajaxloadpost_ajaxhandler’, ‘ajaxloadpost_ajaxhandler’ );

JavaScript Basics and AJAX

With AJAX call and AJAX handler in place, you need to create a JS function that will connect the two dots. The following JavaScript will help you achieve this action which you will put into your ajaxloadpost.js:

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);

}

});

}

Just like the above-mentioned step, this action will also create two outcomes, i.e. nonce and post ID.

The next step requires proficiency in jQuery as well. So, if your skills are a little rustic, you will find this article helpful!

Moving on, use jQuery.ajax function to make an AJAX call to the appropriate servers. In the above codes, the URL is the admin-ajax.php URL which can be found in the JavaScript variable that we registered at the time of enqueuing the scripts. In addition, specify this action with the action handler’s name that was registered with WordPress and also post the nonce and the post ID as well.

If everything goes right, you can update <div> of the id #loadpostresult and replace the fetched content with AJAX handler.

Putting a Face to Your Code

Now, it is time to create codes that will display the appropriate posts’ titles and bring up information which the users desire through an AJAX call. Here are the following codes:

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’ );

Hopefully, this article has helped you in making your WordPress Plugin Responsive. Leave us a comment if you have a query.

Further reading

LEAVE A REPLY