Simple WordPress Plugin to Follow Your Favorite Authors

The incredible growth rate of WordPress has simplified website development. Popular tutorial sites like the Tuts+ network use WordPress to power their websites. These websites provide hundreds of new tutorials, articles and updates daily. So keeping track of every article is not easy even with your RSS feed reader. Your feed reader will be filled with new ones quickly and as readers we are only interested in certain topics. So ideally we would need a method that provides articles that we are interested in. Generally authors specialize in specific areas. If Darren Rowse writes an article about blogging, every one will want to read it. Likewise we have favorite authors that we would like to read every time.

So in this tutorial I am going to create a simple WordPress plugin that lets you subscribe to your favorite authors. You will get an email every time your favorite author publishes a post. Hence you will not miss the important articles ever again.


What Are We Developing Today

Our plugin will basically allow users to get notifications about new posts from subscribed authors. Following are the features and components we will be developing during the tutorial:

  • Creating a Shortcode to list all the authors
  • Allowing users to follow and unfollow authors
  • Send emails when a new post is published

Step 1 Creating the Plugin File

I am not going to explain this step in detail as you may already know that a WordPress plugin file needs to have a comments section at the top to identify the plugin details. I have named the plugin WP Follow Authors. So create a new directory in the /wp-content/plugins directory called wp-follow-authors and create the index.php file with the following details:


Step 2 Creating Tables on Plugin Activation

We need two database tables for this plugin. I am naming them wp_author_subscribe and wp_author_followers (where wp_ will actually be the configured db prefix). The table wp_author_subscribe will keep the subscribers email, activation status and followed authors list. The wp_author_followers table will contain the author id and list of followers. We need to create these tables on plugin activation. So let's consider the following code.

  • We can create a function to be called in plugin activation using register_activation_hook. This is where we should create our database tables.
  • Database tables can be created using a WordPress custom query. But the recommended way is using the dbDelta function to execute the SQL query as shown in the code above.

Step 3 Shortcode for Displaying Authors List

Next we need to display the list of authors available in order for users to follow. So I'll be creating a shortcode which lets you display the author list in any given page. Let's start creating the shortocde.

I have created a shortcode called contributors and a function called contributors to display the author list. All the code related to displaying authors is located inside this function. You have to create a special page to show your contributors. You can name it whatever you would like it to be. Then place the shortcode [contributors] inside the page and click publish button. Still we haven't got any code inside the shortcode function. So let's look into that.

Display Author List

Some blogs allow users to register. They will be created as subscribers generally and subscribers cannot create posts. So when we display the user list, we have to make sure to get the users who have the capability of creating posts. Let's looks at the code below.

  • We get all the users using the get_users function.
  • Then while looping through the user list, we have to check if the user is allowed to publish posts using the user_can function.
  • We create HTML code for details of the authors who can publish posts. I have displayed the author image using gravatar, author display name and description.
  • Next we create a button to follow authors. The important thing here is I have specified a data-author attribute and set the ID of the author.

Now we have the HTML code for displaying authors. So let's look at the code for displaying the subscribe form.

In this simple HTML form we have a text field for a user to enter their email address. Then we have 2 buttons to subscribe and load the followed author list. I'll be using AJAX throughout this plugin. So the ID and classes of HTML elements play a vital role. If you check the actual plugin file, you will notice that I haven't explained the code in the top of the contributors function. It's used to verify the activation and will be explained later. Now we have the complete form with the list of authors and it will look like the tutorial image shown at the top.


Step 4 Configuring JavaScript and CSS

Now the actual functionality part begins and we need some CSS styles and Javascript files to support our functionality. So the following code will show you how to include the necessary scripts and styles in the recommended way.

  • jQuery is the most popular JavaScript library at the moment. So I'll be using jQuery in this plugin. We can enable the version of jQuery included with WordPress by using wp_enqueue_script('jquery')
  • Then we need a CSS file and JS file for our custom functions. So the next 2 lines of code register and include a custom JS file called followjs which is in the plugin folder.
  • Next we register and include the CSS file using the wp_register_style and wp_enqueue_style functions. It's also located in the plugin folder.
  • An important thing to notice is that the plugins_url function will give you the path to the current plugin folder. This is the best way of including scripts. Some people get the plugins directory URL and appends the plugin folder name to get the path. This is not recommended and will cause errors when the plugin folder name gets changed.
  • Finally we add some necessary data to our custom JS script by using the wp_localize_script function.
    • ajaxUrl – Gets the path to ajax file in WordPress.
    • ajaxNonce – Gives a unique key to every ajax request for validation purposes.
    • currentURL – Gets the path to the current URL in order to identify the contributors page.

Step 5 Subscribe to Plugin

In order to follow authors, a user has to subscribe using their email. Once a user enters their email and clicks the Subscribe button they will be subscribed to the service and an email will be sent to activate the service. Let's see what happens when the subscribe button is clicked.

Creating AJAX Request for Subscribing

I have attached a jQuery function using the live event to be called when the Subscribe button (#subscribeAuthors) is clicked. It checks if the email is valid using a regular expression. Then we create the AJAX request to call the subscribe function. I'll explain the AJAX request here.

  • URL is the default ajax page URL which we set when localizing the script in the earlier section.
  • Then we need to set an action to identify the AJAX request from using WordPress. I have used subscribe_to_wp_authors.
  • Next we assign the nonce value created when we localized the script and current page URL.
  • Finally we assign the email address provided and makes the AJAX request. We return the result from server in JSON format. So we prepare the JSON result using the eval function.
  • Based on the success or failure of the request, we assign a message and CSS class to our message display div.

Handling AJAX Request in WordPress

In order to handle AJAX requests from plugin, we can use the following code:

There are actions called wp_ajax_nopriv and wp_ajax to handle AJAX requests for users that are logged out and logged in respectively. These actions are followed by an underscore and the action we defined in the AJAX request from the JS file. So in this case the subscribe_to_wp_authors action will call the subscribe_to_wp_authors function.

"Make sure to use die() at the end of each AJAX function in your PHP code since WordPress returns 0 or -1 depending on the result of the AJAX request which might cause errors in JSON strings."

Let's see what happens inside the function:

  • Initially we get the nonce value sent from AJAX requests against the value we have on the server using the wp_verify_nonce function. Different nonce values means that the AJAX request should be invalid and discarded.
  • Then we get the email sent from the AJAX requests and validate using is_email.
  • Next we make sure the user is not already subscribed by checking with the database table.
  • Then we generate an random activation string and save the subscriber details to the database. Random string generation function can be found in the plugin file.
  • Finally we prepare the activation link by adding the activation code to current page URL and send the email to the user.
  • If everything is done properly, the user should get a screen like the following:

Then once the user clicks the activation link in the email, they will be directed back to the website with an activation success message and their email address will be loaded into the textbox. The activation check is done at the top of the shortcode function. I omitted the explanation earlier, now it's time to take a look at that code in the contributors function.

A user can visit the authors page directly or using the confirmation link. So first we check if the confirm-follow parameter is available in the URL to figure out whether this is an activation request or not. Then we search for an activation in the database table for the activation code provided in the URL. Then we update the user's activation status and display the result message with relative CSS class. Now the whole process of subscribing is completed. Now the user can start following authors.


Step 6 Following Authors

Now the activation is successful and your email is displayed in the email box. This is the time where you can choose authors from the list and click the "Follow" button. Let's see how to make a user follow an author. An AJAX request will be made as soon as you click on the follow button of a specific author.

Each author has a follow button in front of his name which contains a CSS class called follow. So every time a follow button is clicked, the $jq(".follow").live("click") function will be triggered and we can get only the clicked button using $jq(this). Then we make a new AJAX request as earlier with the action follow_wp_authors.

The only difference here is we add an additional parameter called author_id to the request. We can get the author's ID using the data-author attribute we defined in the display section. Now let's just take a look at the PHP code for handling this AJAX request.

We have to add two new actions for this AJAX request as we did earlier. The function follow_up_authors will contain the code used for following an author. Since there's no point explaining repetitive code again and again I am going to explain the sections which are necessary. So I suggest you to look at the function in the plugin file while reading through the tutorial. The initial part of the function will verify the nonce, validate the email, and check for the activation in the database. So let's move forward.

Adding Users for Following

Since we are using custom tables in our plugin, even if there are many authors available in the site, our author table will initially be empty. So when a user clicks the Follow button for an author, we can check if the author is available in our table. If not we make the initial entry by inserting the author into table. Consider the following code:

Receiving Users Followed Authors List

  • We have two tables and we keep a list of authors followed by a user as well as list of users following an author.
  • So we get the author list of current users using the followed_authors column value in the wp_author_subscribe table.
  • If no authors are followed yet, we make an empty array. Otherwise we convert the author list into an array using explode and then check if the user is already subscribed to the author using the in_array function. Then we add the author ID into the user's followed authors list.

Receiving Authors Followers List and Finalizing Follow

  • We received the followed author list of the given user in the previous section. Now we get the followers list of current author
  • Then we add the user to followers list using the same procedure and validations as we did before
  • Then we create author's followers list as a string by imploding $authorSubscribersArray and assigning to a variable called $followersList
  • The same procedure is used to create author's list of current users and assigned to the $subscribedAuthorList
  • Finally we update the new following details to both tables and return the success message using JSON
  • Once you followed an author successfully, you will see that the Follow button will change to Following

Step 7 Unfollowing Authors

If this plugin is to be effective, users might need to have the feature to unfollow authors as well as follow authors at any given time. I'll explain the process of unfollowing an author. Since it's very similar to the following process I am going to omit repetitive codes in the explanation.

The button inline with all the followed authors will be displayed as Following. When you hover on the button, text will change to different color as Unfollow. When clicking on the button another AJAX request will be made to 'Unfollow' the author. Since only the action name is different from the above code, I am not going to include it here. You can take look at $jq(".following").live("click",function(){} in the followjs file.

The function used to unfollow the user is unfollow_wp_authors. This code is similar to the follow author function. We can put the common code into a single function in the future if you are willing to extend the plugin. In the follow authors section we added the author to the list if not already available. In this case we just remove the author from the list if already exists. Code below shows you the changes compared to the follow author function.

You can see that instead of pushing authors to the array, we remove them by using the unset function.


Step 8 Loading Author Following Information

Initially the email address will be empty when you load the page with the author list since we don't have a procedure to identify the current user. Then user has to enter the email and click the load button to get the list with the following details of each user. This is going to be another AJAX request similar to previous ones and you can take a look at the code using $jq("#loadFollowers").live("click",function(){}. I'll explain the result section of the request since it's little bit different to the previous ones.

  • Only the followed author list of given email will be returned in the message variable.
  • Once the result is received code loops through each author box using the CSS class follow and checks if the author is followed by the user.
  • The jQuery inArray function is used for this and it will return -1 if the search string is not found in the array.
  • So we display the text "Following" for the followed class and adds the following CSS class to identify the followed authors.

Let's take a look at the function for loading following author list from server side:

  • We have two actions. Nonce and email validation and check activation as usual in the beginning of the function.
  • Then we get the followed author list for current the email address in the textbox using wp_author_subscribe.
  • Finally we create a followed authors array using the string and pass it using JSON to the client side JS code.

Now users are subscribed to the service and can follow and unfollow authors whenever they want. The final and most important part of the tutorial is sending emails to followers when a post is published by an author. Let's get started.


Step 9 Sending Emails When Posts Are Published

We have to trigger an action when any user publishes a new post. WordPress provides a set of actions called Post Status Transitions to achieve this functionality. I have set up four transitions, which could be triggered when you publish a post.

The above actions will call the notify_author_followers function whenever a post is converted to a published state from one of new, draft, pending or future states. So let's send emails using the notify_author_followers function.

  • An object containing the information about published posts will be passed by default to our notify_author_followers function.
  • First we get the details of the author using the $post object. Then we get the list of followers for the current author from the {$wpdb->prefix}author_followers table.
  • Then we get the emails of users who follow the current author using the {$wpdb->prefix}author_subscribe table.
  • We create the email content by using the post title and author. You can change this to contain any information you want. Also make sure to change the content type to HTML using the wp_mail_content_type function.
  • Add a from name and address to the $emailHeaders variable. Also we don't want users to see other users' email addresses. So add the email list of followers to the Bcc header.
  • Finally send the email using the wp_mail function as shown above.

We have completed the process of creating a basic WordPress plugin to follow authors. Whenever a post is published followers will be notified. It's as simple as that.


Conclusion

I had to create a long tutorial to explain everything in creating this kind of plugin using AJAX. This is still at its most basic level. As a user I would like to have the functionality to follow authors in every blog I read. So as web masters you should consider improving the plugin functionalities letting users follow their favorite authors. You will get a free email subscribers list as a bonus as well. Hope you enjoyed the tutorial and looking forward to comments and suggestions in the comments below.

Update: This article has been updated to factor in corrections mentioned in the comments below by Leonel and Julio.

Tags:

Comments

Related Articles