Advertisement

Simple WordPress Plugin to Follow Your Favorite Authors

by
Student iconAre you a student? Get a yearly Tuts+ subscription for $45 →

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:

<?php
/*
  Plugin Name:  WP Follow Authors
  Version: 1.0
  Plugin URI: http://wp.tutsplus.com/tutorials/simple-wordpress-plugin-to-follow-your-favorite-authors
  Description: Get email notifications when your favorite author publishes a post.
  Author URI: http://www.innovativephp.com
  Author: Rakhitha Nimesh
  License: GPL2
 */
?>

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.

<?php

function wp_authors_tbl_create() {
	global $wpdb;

	require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

	$wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}author_subscribe");

	$sql1 = "CREATE TABLE {$wpdb->prefix}author_subscribe (
		id int(11) NOT NULL AUTO_INCREMENT,
		activation_code varchar(255) NOT NULL,
		email varchar(75) NOT NULL,
		status int(11) NOT NULL,
		followed_authors text NOT NULL,
		PRIMARY KEY (id)
	) ENGINE=InnoDB AUTO_INCREMENT=1;";

	dbDelta($sql1);

	$sql2 = ("CREATE TABLE {$wpdb->prefix}author_followers (
		id int(11) NOT NULL AUTO_INCREMENT,
		author_id int(11) NOT NULL,
		followers_list text NOT NULL,
		PRIMARY KEY (id)
	) ENGINE=InnoDB AUTO_INCREMENT=1;");

	dbDelta($sql2);
}

register_activation_hook(__FILE__, 'wp_authors_tbl_create');
?>
  • 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.

<?php

add_shortcode("contributors", "contributors");

function contributors() {

}

?>

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.

<?php

	$authors = get_users();

	$authorsList = '<div id="wp_authors_list">';
	foreach ($authors as $author) {
		if (user_can($author->ID, 'publish_posts')) {
			$authorsList .= '<div class="auth_row">
					<div class="auth_image">' . get_avatar($author->ID) . '</div>
					<div class="auth_info">
						<p class="title">' . get_the_author_meta('display_name', $author->ID) . '</p>
						<p class="desc">' . get_the_author_meta('description', $author->ID) . '</p>
					</div>
					<div class="auth_follow"><input type="button" class="follow" value="Follow" 
					data-author="' . $author->ID . '" /></div>
					<div class="frm_cls"></div>
				</div>';
		}
	}

	$authorsList .= '</div>';
?>
  • 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.

<?php
$output = '<div id="wp_authors_panel">
	<div id="wp_authors_head">Follow WP Authors</div>
	<div id="wp_authors_form">
		<div class="frm_row">
			<div id="frm_msg" class="' . $actClass . '">' . $actStatus . '</div>
			<div class="frm_label">Enter Your Email</div>
			<div class="frm_field"><input type="text" name="user_email" id="user_email" 
value="' . $confirmedEmail . '" /></div>
			<div class="frm_cls"></div>
		</div>
		<div class="frm_row">
			<div class="frm_label">&nbsp;</div>
			<div class="frm_control"><input type="button" value="Subscribe" id="subscribeAuthors" /></div>
			<div class="frm_control"><input type="button" value="Load" id="loadFollowers" /></div>
			<div class="frm_cls"></div>
		</div>
	</div>
	' . $authorsList . '
</div>';

echo $output;
?>

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.

<?php
function apply_wp_author_scripts() {

	wp_enqueue_script('jquery');

	wp_register_script('followjs', plugins_url('follow.js', __FILE__));
	wp_enqueue_script('followjs');

	wp_register_style('followCSS', plugins_url('follow.css', __FILE__));
	wp_enqueue_style('followCSS');

	$config_array = array(
		'ajaxUrl' => admin_url('admin-ajax.php'),
		'ajaxNonce' => wp_create_nonce('follow-nonce'),
		'currentURL' => $_SERVER['REQUEST_URI']
	);
	wp_localize_script('followjs', 'ajaxData', $config_array);
}

add_action('wp_enqueue_scripts', 'apply_wp_author_scripts');
?>
  • 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

<script>

$jq =jQuery.noConflict();

var emailValidation = function(email) {

	$jq("#frm_msg").html("");
	$jq("#frm_msg").removeAttr("class");

	var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

	if (email == '' || (!emailReg.test(email))) {
		$jq("#frm_msg").html("Please enter valid email");
		$jq("#frm_msg").addClass("error");
		return false;
	}
	else {
		return true;
	}

};

$jq(document).ready(function() {

	/*
	 * Make initial subscription to service
	 */
	$jq("#subscribeAuthors").live("click",function() {

		var email = $jq("#user_email").val();
		if (emailValidation(email)) {

			jQuery.ajax({
				type: "post",
				url: ajaxData.ajaxUrl,
				data: "action=subscribe_to_wp_authors&nonce="+ajaxData.ajaxNonce+"&url="+ajaxData.currentURL+"&email="+email,
				success: function(message) {
					var result = eval('(' + message + ')');
					if (result.error) {
						$jq("#frm_msg").html(result.error);
						$jq("#frm_msg").addClass("error");
					}
					if (result.success) {
						$jq("#frm_msg").html(result.success);
						$jq("#frm_msg").addClass("success");
					}
				}
			});
		}

	});

}

</script>

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:

<?php
add_action('wp_ajax_nopriv_subscribe_to_wp_authors', 'subscribe_to_wp_authors');
add_action('wp_ajax_subscribe_to_wp_authors', 'subscribe_to_wp_authors');
?>

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:

<?php
function subscribe_to_wp_authors() {
	global $wpdb;

	$ajaxNonce = $_POST['nonce'];

	if (wp_verify_nonce($ajaxNonce, 'follow-nonce')) {

		$subscriber_email = isset($_POST['email']) ? $_POST['email'] : '';
		if (is_email($subscriber_email)) {

			$email_result = $wpdb->get_results($wpdb->prepare("select * from {$wpdb->prefix}author_subscribe where email=%s", $subscriber_email));

			if (count($email_result) == '0') {
				$activation_code = generate_random_act_code();

				$result = $wpdb->query($wpdb->prepare("INSERT INTO {$wpdb->prefix}author_subscribe (email,activation_code,status) VALUES ( %s, %s, %s )", $subscriber_email, $activation_code, "unsubscribed"));

				$activation_link = add_query_arg('confirm-follow', $activation_code, get_site_url() . $_POST['url']);

				if ($result) {

					if (wp_mail($subscriber_email, "WP Author Subscription", "Click $activation_link to activate.")) {
						echo json_encode(array("success" => "Please check email for activation link."));
					}
					else {
						echo json_encode(array("error" => "Email Error."));
					}
				}
			}
			else {
				echo json_encode(array("error" => "Email already exists."));
			}
		}
		else {
			echo json_encode(array("error" => "Please enter valid Email"));
		}
	}
	die();
}
?>
  • 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.

<?php
	$confirmedEmail = '';

	if (isset($_GET['confirm-follow'])) {

		$activationCode = $_GET['confirm-follow'];

		$activationCheck = $wpdb->get_results($wpdb->prepare("select * from {$wpdb->prefix}author_subscribe where activation_code=%s and status=0 "), $activationCode);

		if (count($activationCheck) != 0) {
			$activationResult = $wpdb->query($wpdb->prepare("update {$wpdb->prefix}author_subscribe set status=1 where activation_code=%s"), $activationCode);
			if ($activationResult) {

				$confirmedEmail = $activationCheck[0]->email;

				$actStatus = "Activation Successfull";
				$actClass = "success";
			}
			else {
				$actStatus = "Activation Failed";
				$actClass = "error";
			}
		}
	}
?>

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.

<script>
   $jq(".follow").live("click",function() {

		var activeObject = $jq(this);

		var email = $jq("#user_email").val();
		if (emailValidation(email)) {

			jQuery.ajax({
				type: "post",
				url: ajaxData.ajaxUrl,
				data: "action=follow_wp_authors&author_id="+$jq(this).attr("data-author")+"&nonce="+ajaxData.ajaxNonce+"&url="+ajaxData.currentURL+"&email="+email,
				success: function(message) {
					var result = eval('(' + message + ')');
					if (result.status == 'success' ) {
						activeObject.val("Following");
						activeObject.removeClass("follow").addClass("following");
					}
				}
			});
		}

	});
</script>

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.

<?php
add_action('wp_ajax_nopriv_follow_wp_authors', 'follow_wp_authors');
add_action('wp_ajax_follow_wp_authors', 'follow_wp_authors');

function follow_wp_authors() {

}
?>

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:

<?php

	$subscriberID = $emailResult[0]->id;
	$authorId = isset($_POST['author_id']) ? $_POST['author_id'] : '';

	/*
 	 * Check if author exists and insert if not already available to follow
	 */
	$authorResult = $wpdb->get_results($wpdb->prepare("select * from {$wpdb->prefix}author_followers where author_id=%d"), $authorId);

	if (count($authorResult) == '0') {
		$result = $wpdb->query($wpdb->prepare("INSERT INTO {$wpdb->prefix}author_followers (author_id) VALUES (%d)", $authorId));
	}

?>

Receiving Users Followed Authors List

<?php

	/*
	 * Get Author List of the Current User
	 */
	$subscribedAuthorList = $emailResult[0]->followed_authors;
	if ($subscribedAuthorList != '') {
		$subscribedAuthorList = explode(",", $subscribedAuthorList);
	}
	else {
		$subscribedAuthorList = array();
	}

	if (!(in_array($authorId, $subscribedAuthorList))) {
		array_push($subscribedAuthorList, $authorId);
	}

?>
  • 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

<?php
	/*
	 * Get current author info with authers subscribers
	 */
	$authorResult = $wpdb->get_results($wpdb->prepare("select * from {$wpdb->prefix}author_followers where author_id=%d"), $authorId);

	if (count($authorResult) == '1') {

		if ($authorResult[0]->followers_list != '') {
			$authorSubscribersArray = explode(",", $authorResult[0]->followers_list);
		}
		else {
			$authorSubscribersArray = array();
		}

		if (!(in_array($subscriberID, $authorSubscribersArray))) {
			array_push($authorSubscribersArray, $subscriberID);
		}

		// User list who follows specific author
		$followersList = implode(",", $authorSubscribersArray);

		// Author list followed by specific user
		$subscribedAuthorList = implode(",", $subscribedAuthorList);

		$result = $wpdb->query($wpdb->prepare("update {$wpdb->prefix}author_followers set followers_list=%s where author_id=%d"), $followersList, $authorId);

		$result = $wpdb->query($wpdb->prepare("update {$wpdb->prefix}author_subscribe set followed_authors=%s where email=%s"), $subscribedAuthorList, $subscriberEmail);

		echo json_encode(array("status" => "success"));
	}
?>
  • 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.

<?php
	foreach ($subscribedAuthorList as $key => $value) {
		if ($authorId == $value) {
			unset($subscribedAuthorList[$key]);
		}
	}

	foreach ($authorSubscribersArray as $key => $value) {
		if ($subscriberID == $value) {
			unset($authorSubscribersArray[$key]);
		}
	}
?>

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.

<script>
	$jq("#loadFollowers").live("click",function() {
		var email = $jq("#user_email").val();
		if (emailValidation(email)) {

			jQuery.ajax({
				type: "post",
				url: ajaxData.ajaxUrl,
				data: "action=load_subscribed_authors&nonce="+ajaxData.ajaxNonce+"&email="+email,
				success: function(message) {
					var result = eval('(' + message + ')');
					$jq(".follow").each(function() {
						var actObj = $jq(this);

						var searchedIndex = ($jq.inArray($jq(this).attr("data-author"), result.authors));
						if (searchedIndex != -1) {
							actObj.val("Following");
							actObj.removeClass("follow").addClass("following");
						}
					});
				}
			});
		}
	});
</script>
  • 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:

<?php
add_action('wp_ajax_nopriv_load_subscribed_authors', 'load_subscribed_authors');
add_action('wp_ajax_load_subscribed_authors', 'load_subscribed_authors');

function load_subscribed_authors() {
	global $wpdb;

	$ajaxNonce = $_POST['nonce'];

	if (wp_verify_nonce($ajaxNonce, 'follow-nonce')) {

		$subscriber_email = isset($_POST['email']) ? $_POST['email'] : '';
		if (is_email($subscriber_email)) {

			$email_result = $wpdb->get_results($wpdb->prepare("select * from {$wpdb->prefix}author_subscribe where email=%s and status=1 "), $subscriber_email);

			if (count($email_result) == '1') {

				$subscriberID = $email_result[0]->id;

				$authorResult = $wpdb->get_results($wpdb->prepare("select * from {$wpdb->prefix}author_subscribe where id=%d"), $subscriberID);

				if (count($authorResult) != '0') {
					$userFollowedAuthors = $authorResult[0]->followed_authors;
					$userFollowedAuthors = explode(",", $userFollowedAuthors);
					echo json_encode(array("authors" => $userFollowedAuthors));
				}
			}
		}
		else {
			echo json_encode(array("error" => "Please enter valid Email"));
		}
	}

	die();
}
?>
  • 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.

<?php
add_action('new_to_publish', 'notify_author_followers');
add_action('draft_to_publish', 'notify_author_followers');
add_action('pending_to_publish', 'notify_author_followers');
add_action('future_to_publish', 'notify_author_followers');
?>

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.

<?php
function notify_author_followers($post) {
	global $wpdb;

	$publishedPostAuthor = $post->post_author;

	$authorDisplayName = get_the_author_meta('display_name', $publishedPostAuthor);

	$authorsFollowers = $wpdb->get_results($wpdb->prepare("select * from {$wpdb->prefix}author_followers where author_id=%d"), $publishedPostAuthor);

	if (count($authorsFollowers) == '1') {
		$authorsFollowersList = $authorsFollowers[0]->followers_list;

		if ($authorsFollowersList != '') {
			$authorsFollowersEmails = $wpdb->get_results($wpdb->prepare("select email from {$wpdb->prefix}author_subscribe where id in(%s)"), $authorsFollowersList);

			$bccList = '';

			foreach ($authorsFollowersEmails as $key => $emailObject) {
				$bccList .= $emailObject->email . ",";
			}

			$bccList = substr($bccList, 0, -1);

			$postMessage = "<a href='$post->guid'><h2>$post->post_title</h2>";

			$emailHeaders .= "From: WP Follow Authors <example@wpauthorplugins.com>" . "\r\n";
			$emailHeaders .= "Bcc: $bccList" . "\r\n";

			add_filter("wp_mail_content_type", create_function("", 'return "text/html";'));
			if (wp_mail("admin@example.com", "New Post From $authorDisplayName", $postMessage, $emailHeaders)) {
				
			}
		}
	}
}
?>
  • 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.

Advertisement