Using AJAX and PHP in Your WordPress Site Creating Your Own Plugin
Good design is invisible! It’s like an air conditioner set on automatic temperature control. Until you feel too hot or cold, you don’t pay any attention to it, concentrating instead on the task at hand, or just enjoying your time.
For users surfing the web, Ajax is like an automatic air conditioner. It makes websites smoother and faster to use, resulting in a pleasurable experience. And most importantly, it just works!
If you prefer a video instead, you’re in luck!
What is Ajax Exactly?
You’ve probably come across Ajax on the web already. Google Search’s autocomplete feature is perhaps the most popular one. Google Maps is another. Live refresh of tweets, Facebook comments, Reddit posts, YouTube likes, all these incredible user experiences are made possible thanks to Ajax and related technologies.
In this post, I’ll give you a quick intro to Ajax, list its advantages, explain how it works in WordPress, and then we’ll dive headfirst into creating a simple WordPress Ajax Plugin.
Sounds fun? Let’s get started.
The Basics of Ajax
Here’s how it usually goes:
- A user action triggers an event in a browser (like a button click).
- The Ajax call activates, which sends a request to the server, using XML/JSON.
- The server-side script processes this request. It can also access the database if it needs to.
- The server then sends a response back to the browser.
The Many Advantages of Ajax
- Minimizes bandwidth usage and optimizes network operations, as the servers won’t be required to process loads of data.
- Saves time for both the users and the server, as the user can see the response from the server immediately.
- Increased performance. Since no full-page data is being sent, Ajax improves the performance, speed, and usability of web pages/apps.
- Increased responsiveness. By eliminating full-page reload, websites will be swifter and highly responsive, thus more user-friendly.
Skills Needed to Work with Ajax in WordPress
- Basic familiarity with XML or JSON data interchange formats
- Know-how of PHP for server-side scripting
If your jQuery or PHP knowledge is touch and go, don’t fret! You can still follow the tutorial logic. Feel free to hop into the comments section if you’re stuck or need help with something :)
Intro to Ajax in WordPress
The core of WordPress already uses Ajax, but only in the admin screens. For instance, when you’re moderating comments or adding/deleting items from categories or posts, you can see instant updates thanks to Ajax. It’s also the tech behind the much loved auto-save functionality.
Ajax is most commonly used with jQuery functions on WordPress, as it’s much simpler when compared to VanillaJS. Moreover, WordPress core already comes loaded with the jQuery library.
Here’s what the process for using Ajax in WordPress looks like:
- The user triggers an Ajax request, which is first passed to the admin-ajax.php file in the wp-admin folder.
- The Ajax request needs to supply at least one piece of data (using the GET or POST method). This request is called the action.
- The code in admin-ajax.php uses the action to create two hooks: wp_ajax_youraction and wp_ajax_nopriv_youraction. Here, youraction is the value of the GET or POST variable action.
- The first hook wp_ajax_youraction executes only for logged-in users, while the second hook wp_ajax_nopriv_youraction caters exclusively for logged-out users. If you want to target all users, you need to fire them both separately.
Let’s Create a WordPress Ajax Plugin
Every great journey begins with a single step, and so does our learning. Let us build a basic WordPress plugin called Post Likes Counter with the following features:
- Logged-in users can like posts.
- The plugin keeps a tally of the total number of post likes and displays them.
- The post likes counter is updated instantaneously on the front-end.
- Logged-out users will be shown an error message if they attempt to like a post.
To start, create an empty WP plugin and activate it. If you need help with this, you can refer to our WordPress plugin development guide. WordPress Codex also has a detailed page on writing a WP plugin.
Find Your Theme’s Post Template
After that, you need to find your theme’s single.php post template. It’s used when a single post is queried, which is where we want our post likes counter to be. This file can be found in the root folder of your active theme. Keep it open for editing.
Get the Post Template Ready for an Ajax Call
Alternatively, you can add this code to any of the template parts your single.php file includes. For instance, if you’re using the official Twenty Nineteen theme, you can insert this code in your theme’s content-single.php file. For testing this plugin code, I inserted it in this file at the very end of its div.entry-content section.
Clicking the link created above will take you to the admin-ajax.php script, but you won’t see any useful output as you’ve not created any function yet to run your action.
To do that, create a function in your plugin file and add it to the two hooks that were created by WordPress for you. Follow the code shown below:
The function to handle logged-out users doesn’t do much here except for throwing up an error message. It’s only meant to serve as an example. You can, of course, build on this and give your visitors more helpful options.
And that’s it! Hurrayyyyyy!
You’ve now enabled Ajax functionality for your plugin. Of course, you can expand on this and add more features as per your liking. Go ahead, tweak it till you make it!
Notable WordPress Plugins Which Use Ajax
Need some Ajax inspiration to fire you up? Check out these amazing WordPress plugins that use the power of Ajax to build powerful features and smoother user experiences.
- Lazy Load Plugins
Lazy Loading is a web development technique used to improve initial page loading time. It’s done by delaying the loading of resource-heavy assets that aren’t visible to the user in their browser’s viewport. These assets are loaded automatically when the user scrolls down the web page. The free version of Smush supports lazy loading.
A completely expandable form maker plugin that also supports polls, quizzes, order forms with payment options, etc. It has an option to enable form submissions with Ajax, making it a seamless experience for the users.
- Login With Ajax
Power your WordPress site with smooth Ajax login and registration effects with this feature-rich plugin. If you’re looking to give your users a better login and registration experience than the default WordPress one, look no further.
This simple plugin adds an Ajax rating system for your WordPress website’s posts and pages. It also adds shortcode support for the ratings, so that you can display them anywhere you want.
- YITH WooCommerce Ajax Product Filter
An extremely helpful and powerful plugin for WooCommerce that lets you apply the exact filters you need to display the product variations you’re looking for. Ajax makes sure that it all happens in a jiffy.
- Ajax Search Lite
A responsive, live search plugin for WordPress, powered by Ajax. It also includes Google autocomplete and keyword suggestions. Give your users a better search experience on your website with this plugin.
- Simple Ajax Chat
Have you ever wondered if you could chat with other users on a website, live? This Ajax-powered plugin is the answer to that. It’s mobile compatible and is built to be extremely customizable as per your liking.
Head over to WordPress.org’s plugin repository for more brilliant Ajax implementations.
Keep Calm and Ajax On!
What’s good for the <body> is good for the user and server too, but you need to balance it out. Ajax is a powerful tool in your arsenal to enhance website performance and user experience. But you should only use it where it’s necessary. Always focus on the user experience aspect. It’ll be a bit rough in the beginning, but once you’ve mastered the basics of Ajax, there’s no stopping you!Tags: