Shop Categories

X

Using AJAX with PHP on Your WordPress Site with Your Own Plugin

In the last couple of years, the need for building increasingly dynamic and interactive websites has intensified. Web developers want to deliver better web experiences to users, and AJAX is helping them accomplish these goals. 

What Is AJAX?

The entity stands for Asynchronous JavaScript And XML and comprises of web development techniques that help create asynchronous web applications. This technology can automatically update the contents and information on a webpage without having to reload it manually. The process takes place in the background without disrupting whatever the user is doing on the webpage, thereby maintaining the quality of the user experience. 

Advantages Of AJAX 

  • Response time from the server is faster so the user can save time. 
  • Ajax is designed to increase the performance, loading speed, and usability websites and applications. 
  • Websites using AJAX are highly responsive since the content is automatically updated in the background without requiring a full-page reload. 
  • Reduces the bandwidth usage and improves network operations, so the system isn’t burdened with vast volumes of data.

WordPress and AJAX

Fortunately, AJAX is already integrated into the back end of WordPress, so you just need to understand how to use whatever’s available. Normally, AJAX is initiated by jQuery functions present in the WordPress library. The function enables you to send fragments of data to the server for processing. The following is an excerpt of the code: 

var data {
	action: "spyr_plugin_do_ajax_request",
	var1: "value 1",
	var2: "value 2"
}

The user prompts an AJAX request, which is sent to admin-ajax.php file located in the wp-admin folder of your WordPress site. 

Every request is required to deliver a minimum of one bit of data called to action. According to this action, the code in admin-ajax.php creates two WordPress dedicated hooks, wp_ajax_my_action and wp_ajax_nopriv_my_action. In this case, my_action is known as the value of GET or POST variable action. 

The first function is executed only if the user is logged in, while the second can work for logged-out users accordingly. If your aim is to target all the users, then both the actions must be implemented separately. 

How to Create an AJAX Plugin for WordPress? 

To kick-start your learning process, let’s begin by creating a basic WordPress plugin called ‘Post Likes Counter’ which will consist of a set of features: 

  • All logged-in users can like posts 
  • Logged-out users that attempt to like the post will receive an error message 
  • The counter assigned for post likes updates automatically in the front-end 
  • The plugin is designed to keep a score of the total number post likes and display them next to the post. 

The next step is to locate your theme’s single.php post template. This request is implemented when an individual post is queried, and this is where your post likes counter will be positioned. The file will be present in the folder of your active theme and should be kept open for editing.

Setting Up the Post Template for An AJAX Request

Starting off, you create a link with a post for users to like. If the user’s browser supports JavaScript, then it will use the JavaScript file, otherwise, it will simply follow the link. Next, paste the code script below in your single.php file. 

// The 'likes' meta key value will store the total like count for a specific post, it'll show 0 if it's an empty string
<?php
	$likes = get_post_meta($post->ID, "likes", true);
	$likes = ($likes == "") ? 0 : $likes;
?>
 
This post has <span id="like_counter"><?php echo $likes ?></span> likes<br>
// Linking to the admin-ajax.php file. Nonce check included for extra security. Note the "user_like" class for JS enabled clients.
<?php
	$nonce = wp_create_nonce("my_user_like_nonce");
	$link = admin_url('admin-ajax.php?action=my_user_like&post_id='.$post->ID.'&nonce='.$nonce);
	echo '<a class="user_like" data-nonce="' . $nonce . '" data-post_id="' . $post->ID . '" href="' . $link . '">Like this Post</a>';
?>

Another option would be to place this code in any template components of your single.php file. Whatever theme you’re using, just insert the code in the theme’s content-single.php file and then run the code to test it out. 

Implementing the AJAX Request Without Using JavaScript 

When you click the link that was created above, it should take you to the admin-ajax.php script, however; there won’t be any significant output value as you haven’t created a function to fire the action. 

To do this, simply create a function in your original plugin file and add the function to the two hooks generated by WordPress. Then, use the code displayed below:

<?php // used here only for enabling syntax highlighting. Leave this out if it's already included in your plugin file.
 
// define the actions for the two hooks created, first for logged in users and the next for logged out users
add_action("wp_ajax_my_user_like", "my_user_like");
add_action("wp_ajax_nopriv_my_user_like", "please_login");
 
// define the function to be fired for logged in users
function my_user_like() {
   
   // nonce check for an extra layer of security, the function will exit if it fails
   if ( !wp_verify_nonce( $_REQUEST['nonce'], "my_user_like_nonce")) {
      exit("Woof Woof Woof");
   }   
   
   // fetch like_count for a post, set it to 0 if it's empty, increment by 1 when a click is registered 
   $like_count = get_post_meta($_REQUEST["post_id"], "likes", true);
   $like_count = ($like_count == '') ? 0 : $like_count;
   $new_like_count = $like_count + 1;
   
   // Update the value of "likes" meta key for the specified post, creates new meta data for the post if none exists
   $like = update_post_meta($_REQUEST["post_id"], "likes", $new_like_count);
   
   // If above action fails, result type is set to "error" and like_count set to old value, if success, updated to new_like_count  
   if($like === false) {
      $result['type'] = "error";
      $result['like_count'] = $like_count;
   }
   else {
      $result['type'] = "success";
      $result['like_count'] = $new_like_count;
   }
   
   // Check if action was fired via Ajax call. If yes, JS code will be triggered, else the user is redirected to the post page
   if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
      $result = json_encode($result);
      echo $result;
   }
   else {
      header("Location: ".$_SERVER["HTTP_REFERER"]);
   }
 
   // dont forget to end your scripts with a die() function - very important
   die();
}
 
// define the function to be fired for logged out users
function please_login() {
   echo "You must log in to like";
   die();
}

In doing so, when a signed-in user likes the post link, the counter should automatically increase by 1 and display it as so. The browsers that don’t have JavaScript enabled will reload the page to display the new like count. For instance, the blog web page of a software development company can have ‘Like this post’ button next to each article piece, and whenever a logged-in user likes the post, the number will increase. 

Wrapping Up 

It’s totally your call if you want to build more and include other features in your code. The process of learning AJAX is pretty straightforward on WordPress, and the quicker you get the hang of it, the better your sites become. AJAX is a solid tool to have in your web development toolkit and can make a great impact on the quality of your website.

About Author

Experienced WordPress developer with over 10 years of full time developing WordPress themes and plugins.

You May Also Like

Comments

Leave a Comment