A Primer on Ajax in the WordPress Frontend: Actually Doing It

In this series, we're discussing how to implement Ajax in the WordPress frontend. In the first post in the series, we reviewed how Ajax works at a high-level, reviewed how to introduce Ajax into the Dashboard of WordPress, and reviewed the two hooks available for incorporating Ajax into WordPress.

At this point, it's time to actually build something that will demonstrate how we can use Ajax in the WordPress frontend. To do this, we'll be writing our own plugin making sure that we're following WordPress best practices along the way.

By the end of this article, we'll have a fully working plugin with source code publicly available on GitHub. With that said, let's get started.


Planning It Out

If you've read any of my previous articles, then you know that I always like to begin my projects with planning out what we're going to do. This project is no different.

In this example, we're going to be introducing a checkbox that allows readers who are logged into a WordPress site to check off blog posts that they've read. This way, they'll only see posts that they've yet to read since logging into the site.

To build this, we'll be using a couple of things:

  • A fresh install of WordPress
  • The WordPress Theme Unit Test to provide us with plenty of example content
  • The Twenty Eleven theme (since it's so widely available)
  • A user account who has the 'Subscriber' role

Once you have the environment setup, here's the plan of action that we'll be following for our plugin:

  • We'll create a new plugin in the plugins directory called I've Read This (in the directory ive-read-this)
  • On each post, we'll introduce a checkbox and a label that allows users to mark that they've read this post
  • Once the post has been marked as read, the option will disappear from view

Got it? Go ahead and login as the user that you created with the 'Subscriber' role and let's get started!


Building I've Read This

Once you've got the test data imported, your setup should look something like this:

From here, we're ready to get started writing the plugin.

Stubbing Out the Plugin

Before we actually write any code, I like to go ahead and stub out the plugin files. This means that we'll setup the directory, the basic plugin structure, and any directories that we may need to use for plugin dependencies.

Since we'll be providing some light styling as well as JavaScript files for initiating the Ajax request, here's what the basic directory structure should look like. The lang directory is optional, though I consider it a best practice:

Now, let's stub out the text required for the plugin.php. Note that this will be nothing but a skeleton. It will be primarily responsible for laying the foundation for what we'll be building later in the article:

At this point, you can actually activate the plugin in the WordPress plugin dashboard, though nothing will actually happen. If you're up for it, go ahead and do that now - you'll be able to watch the plugin come to life as we work on it.

Introduce a Checkbox on Each Post

Since we're going to be introducing a checkbox on each post that allows users to toggle whether or not they've read the post, we'll need to account for the following:

  • We need to make sure that the checkbox is only displayed when the user is logged in
  • The checkbox should be at the bottom of the post on the single post page since that's where user's will mark that they've read the post

We can achieve both of these by adding the following function:

Read the comments carefully as they should explain exactly what's going on; however, if you're unclear, don't hesitate to leave a comment.

Next, we need to add the following line in the constructor so that the_content filter is called:

Finally, let's add a little bit of style just to give the checkbox a slightly unique look and feel within the context of the Twenty Eleven theme. In the plugin's plugin.css file, add the following code:

Now, if you log into the WordPress installation and navigate to the bottom of a single post, you should see something like the following image:

At this point, we're ready to begin writing some JavaScript.

Making a Request: Setup the Click Handler for the Checkbox

The first thing that we need to do is to setup the JavaScript so that it only fires if the "I've Read This" container is on the page. There are a variety of ways to do this, but since we're loading the JavaScript on every page, then we'll use JavaScript to check for the presence of the "I've Read This" check box that we're writing out to the page.

To do this, add the following code to plugin.js. The code comments should be self-explanatory. If not, leave a comment!

In the code that you see above, anything that we place within the conditional will only fire if the "I've Read This" container element is present.

In this case, we know that we need to send the ID of the post to the server. Since the user is logged in, we'll be able to get his/her ID on the server side.

So, the next step is to get the ID of the post that we're on. Luckily, Twenty Eleven stores the number of the post in the article element's ID. We just need to parse it out.

Let's do that now:

At this point, we're ready to setup an Ajax request. We'll be using jQuery's $.post method for doing this and we'll be using WordPress' standard ajaxurl to handle our response.

Handling the Event: Mark the Post as Read

Let's go ahead and write the code that will send the ID of the post across. We'll worry about the response later in this article, hence the "TODO" comment in the code.

At this point in development, the full JavaScript source should look like this:

For those of you who have been working through the example code as you've read the article, you'll immediately notice that your browser throws a console error:

Uncaught ReferenceError: ajaxurl is not defined

Oops! And this is where we need to make sure to properly include WordPress' Ajax library.

Including WordPress' Ajax Library on the Frontend

To do this, we'll need to hook into the wp_head action. Add the following line of code in the constructor of your plugin:

Next, add the following function. This is what's actually responsible for including the Ajax library:

Now, if you try to execute the code, you should have no problem. At this point, we're ready to keep going.

Handle the Event: Mark the Post as Read

Now that we've got the request being sent to the server, we can write our server-side event handler. This is how the handler should operate:

  • Check that the incoming Post ID value is set and that it's a numeric value (this is very rudimentary spoof protection, but it works for all intents and purposes).
  • Next, try to update the current user's meta using his/her ID and the post ID.
  • If the update fails, we'll return -1; otherwise, we'll return 1. We'll handle these values in the response handler in the JavaScript.

First, we'll add the hook in the constructor of the plugin:

Next, we'll actually implement the handler:

To that end, let's revisit the outstanding TODO in the response function of the JavaScript that we were working on. Here's the full script:

One More Change

If the user happens to find their way to an individual post page (such as being linked to it), we should check to see if they've previously marked it to be read.

To do this, we need to refactor the add_checkbox function so that it checks to see if the user is logged in and it reads the user meta to determine if the post has been previously marked as read:

See It in Action!

At this point, you've got a working plugin:

  • You should be able to navigate to any post
  • If you've not read it, then you should be able to click on the checkbox and have it disappear
  • If you reload the page, then you'll see the notification that the post has been marked as read.

Not bad, right?

Of course, there's always room to experiment on your own with this. For example, you could work on excluding these posts from the main loop if they've been marked as read. Another option would be to add a custom classname and then styling the post to indicate that the current user has read it.

Finally, remember that you can grab all of the source code in its entirety on GitHub.


Related Reading

Tags:

Comments

Related Articles