Search

How to Create a Recent Post Subscription Plugin in WordPress

Listen to this article
Subscribe-Recent-Post-Plugin-WordPress
Send Email Notification to User on Post Published

WordPress has a good deal of newsletter plugins. Some plugins even connect to third party email marketing services. But such plugins might be an overkill for certain websites. Some websites (may be one like yours), might need a simple, light-weight newsletter plugin. So how do you decide on one?

Let me ask you a few questions:

  • Is your blog the most important section on your website?
  • Do you want users to subscribe to your blog?
  • Do you want to notify readers, every time a new article has been posted?

If you’ve answered ‘yes’ to all of these questions, the newsletter plugin you need, is the Subscribe to Recent Posts Plugin. But hold on. This isn’t any plugin you’ll directly find on WordPress.org. But worry not, today is your lucky day. We’ll help you build it.

So let’s begin.

[space]

Step 1: Create a WordPress Plugin

We need to start by creating a simple WordPress plugin. In your wp-content/plugins directory, create a new folder and name it ‘Recent Post Subscription’. Inside the folder create a file ‘rcp-subscription.php’. Add the needed headers in the file as below:

<?php
/**
* Plugin Name: Recent Post Subscription
* Description: Allow a user to subscribe to recent articles posted on your blog.
* Version: 1.0.0
* Author: <your-name>
*/

For now, we’ll leave the file as is. We’ll continue with the next steps, and keep on adding code as needed.

[space]

Step 2: Allow Readers to Subscribe

Now, we can’t send out notifications, without email ids of interested readers. So we need an option on our site, to allow readers to subscribe to our blog. We’ll add a simple form, with an email input field, and a subscribe button (similar to the one I have in the sidebar).

Email-Subscription-Form
Email Subscription Form

Create a Form

To add a form, insert the following code in rcp-subscription.php:

function rcps_display_form()
{
   return '<h3>Subscribe to Our Recent Posts:</h3>
   <form>
   <p><input type="text" id="rcps_contact_email" name="rcps-email" placeholder="Email"></input></p><br/>
   <p><input type="submit" id="rcps_submit" value="Subscribe Now!" /></p>
   </form>';
}

To add validation to the input field, you can read: Add Real Time Form Validation Using jQuery

You can use a shortcode, to manage the display of the form. For example, if you create a shortcode ‘rcps-display-form’, add the following in rcp-subscription.php:

add_shortcode( 'rcps-display-form', 'rcps_display_form');

For more information on shortcodes, you can read: How to Create Shortcodes in WordPress

Save Email Addresses

Every time a reader subscribes using the form, you want to save his/her email address. But first we need to get the email id. This can be done using some jQuery and AJAX. Do not get flustered, I’ve got you covered.

Create a rcps.js file in a /js/ folder inside your plugin, and add the following code:

jQuery(document).ready(function($) {
  jQuery('#rcps_submit').click(function() {
  var email =jQuery('#rcps_contact_email').val();
  var data = {
              'action': 'rcps_subscription',
              'email': email
             };
  jQuery.post(/*url should be similar to admin_url('admin-ajax.php')*/ , data, function(response) {
      });
  });
});

The above script, posts an event, every time a user subscribes, using your form. Remember to enqueue the script, rcps.js.

You need to then save the email-id in a custom table. This table has to be created on the plugin activation hook, using the below code:

function rcps_on_activation(){
  // create the custom table
  global $wpdb;
  $table_name = "rcps-email-subscribers";  
  $sql = "CREATE TABLE IF NOT EXISTS $table_name (
        ID  bigint(20) AUTO_INCREMENT primary key,
        email_id varchar(50) NOT NULL default '')"$charset_collate;
       require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
       dbDelta( $sql );
 }
register_activation_hook( __FILE__, 'rcps_on_activation' );

You can then save email addresses, in the table as follows:

function rcps_subscription_callback() {
         global $wpdb;
         $email = $_POST['email'];
         $fetch_sql_query = "select * from rcps-email-subscribers where email_id='$email'";
         $result = $wpdb->get_results($fetch_sql_query);
         if(!empty($result))
         {     
             //Insert new row
            $table = 'rcps-email-subscribers';
            $data = array('email_id' => $email);        
            $wpdb->insert($table,$data);
          }//if ends
}
add_action('wp_ajax_rcps_subscripton', 'rcps_subscription_callback' );
add_action('wp_ajax_nopriv_rcps_subscripton','rcps_subscription_callback' );

[space]

Step 3: Notify Readers when an Article is Posted

The final step is to send out emails to subscribed readers. This can be done every time a new post has been submitted.

Send Emails

Add the following in your plugin’s main file, rcp-subscription.php:

function on_post_publish( $ID, $post ) {
            global $wpdb;
            $fetch_sql_query = "select * from rcps-email-subscribers where email_id='$email'";
            $email_subscribers = $wpdb->get_results($fetch_sql_query);
    
           foreach($email_subscribers as $email)
           { 
               // send an email using wp_mail
           }
}
add_action(  'publish_post', 'on_post_publish', 10, 2 );

The above function sends out an email, every time a new post is published.

[space]

And done! Phew! That was a whole lot of code.

Did you get through it okay? I hope you got your plugin ready.

There are certain gaps you could fill, like adding a text domain, or making the plugin multisite ready, and of course adding the needed CSS.

In case you needed any help, you could surely write your questions to me using the comment section below.

Sagar Kale

Sagar Kale

2 Responses

Leave a Reply

Your email address will not be published. Required fields are marked *

Get The Latest Updates

Subscribe to our Newsletter

A key to unlock the world of open-source. We promise not to spam your inbox.

Suggested Reads

WordPress Development

Custom WordPress Solutions, for You

LearnDash Development

Custom LearnDash Solutions, for You

WooCommerce Development

Custom WooCommerce Solutions, for You

WordPress Plugins

Scale your WordPress Business

WooCommerce Plugins

Scale your WooCommerce Business

LearnDash Plugins

Scale your LearnDash Business

Label

Title

Subtext

Label

Title

Subtext

Join our 55,000+ Subscribers

    The Wisdm Digest delivers all the latest news, and resources from the world of open-source businesses to your inbox.

    Suggested Reads

    WordPress Tips & Tricks
    Ketan Vyawahare

    How to Make Responsive Tables using CSS without Tag Read More »