How to Build a Custom Subscription Plugin for WordPress with Email Confirmation and CSV Export Feature

How to Build a Custom Subscription Plugin for WordPress with Email Confirmation and CSV Export Feature

In this tutorial, we’ll walk through creating a Custom Subscription Plugin for WordPress. The plugin will allow visitors to subscribe to your website's newsletter, send them a confirmation email after subscribing, and enable the admin to export the subscriber list in a CSV format.

Key Features of This Plugin:

  • Collects email subscriptions from visitors.
  • Sends a confirmation email to the subscriber after they sign up.
  • Allows the admin to export the list of subscribers as a CSV file.

Let’s dive in!

Step 1: Creating the Plugin Folder and File

First, create a new folder in the wp-content/plugins directory. Name it custom-subscription-plugin. Inside this folder, create a file named custom-subscription-plugin.php.


    <?php
    /*
    Plugin Name: Custom Subscription Plugin with Email Confirmation
    Description: A custom plugin that collects email subscriptions, sends email confirmation to subscribers, and allows CSV export of subscriber data.
    Version: 1.0
    Author: Your Name
    */

    // Prevent direct access to the file
    if (!defined('ABSPATH')) {
        exit;
    }
    ?>
    

Step 2: Creating the Database Table for Subscribers

When the plugin is activated, we need to create a table in the database to store the subscriber emails. This table will also track the subscription date.


    function csp_create_table() {
        global $wpdb;
        $table_name = $wpdb->prefix . 'subscribers';
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE $table_name (
            id mediumint(9) NOT NULL AUTO_INCREMENT,
            email varchar(255) NOT NULL UNIQUE,
            subscribed_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
            PRIMARY KEY (id)
        ) $charset_collate;";

        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }
    register_activation_hook(__FILE__, 'csp_create_table');
    

Step 3: Creating the Subscription Form

We will create a subscription form that users can use to sign up for notifications. This form will be added to a page or post using a WordPress shortcode.


    function csp_subscription_form() {
        ob_start(); ?>
        <form method="post" action="">
            <input type="email" name="csp_email" placeholder="Enter your email" required />
            <button type="submit">Subscribe</button>
        </form>
        <?php
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['csp_email'])) {
            csp_save_email($_POST['csp_email']);
        }
        return ob_get_clean();
    }
    add_shortcode('subscription_form', 'csp_subscription_form');
    

Step 4: Saving Subscriber Emails and Sending Confirmation Email

Next, we’ll handle the saving of emails into the database and send a confirmation email to the subscriber.


    function csp_save_email($email) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'subscribers';

        if (is_email($email)) {
            $existing_email = $wpdb->get_var($wpdb->prepare("SELECT email FROM $table_name WHERE email = %s", $email));
            if (!$existing_email) {
                $wpdb->insert($table_name, ['email' => sanitize_email($email)]);
                echo '<p>Thank you for subscribing!</p>';

                // Send confirmation email
                $subject = 'Subscription Confirmation';
                $message = 'Thank you for subscribing to our website. You will now receive notifications for new posts.';
                $headers = ['Content-Type: text/html; charset=UTF-8'];

                // Send email to the subscriber
                wp_mail($email, $subject, $message, $headers);
            } else {
                echo '<p>You are already subscribed!</p>';
            }
        } else {
            echo '<p>Please enter a valid email address.</p>';
        }
    }
    

Step 5: Displaying the Subscriber List in the Admin Panel

Now we need an admin page where the site administrator can see a list of subscribers and export it to a CSV file. We’ll create an admin menu for this purpose.


    function csp_admin_menu() {
        add_menu_page(
            'Subscribers',
            'Subscribers',
            'manage_options',
            'csp-subscribers',
            'csp_subscribers_page',
            'dashicons-email',
            20
        );
    }
    add_action('admin_menu', 'csp_admin_menu');
    

On this page, we’ll display the list of subscribers and provide a button to export them to CSV:


    function csp_subscribers_page() {
        global $wpdb;
        $table_name = $wpdb->prefix . 'subscribers';
        $subscribers = $wpdb->get_results("SELECT * FROM $table_name");

        echo '<div class="wrap">';
        echo '<h1>Subscribers</h1>';

        // Export button
        echo '<form method="post">';
        echo '<input type="submit" name="export_subscribers" value="Export Subscribers as CSV" class="button button-primary" />';
        echo '</form>';

        if (isset($_POST['export_subscribers'])) {
            csp_export_subscribers_to_csv($subscribers);
        }

        // Display subscriber table
        echo '<table class="widefat fixed" cellspacing="0">';
        echo '<thead><tr><th>ID</th><th>Email</th><th>Subscribed At</th></tr></thead>';
        echo '<tbody>';
        foreach ($subscribers as $subscriber) {
            echo '<tr>';
            echo '<td>' . esc_html($subscriber->id) . '</td>';
            echo '<td>' . esc_html($subscriber->email) . '</td>';
            echo '<td>' . esc_html($subscriber->subscribed_at) . '</td>';
            echo '</tr>';
        }
        echo '</tbody>';
        echo '</table>';
        echo '</div>';
    }
    

Step 6: Exporting Subscribers to CSV

When the export button is clicked, the subscriber data will be downloaded as a CSV file.


    function csp_export_subscribers_to_csv($subscribers) {
        if (empty($subscribers)) {
            echo 'No subscribers to export.';
            return;
        }

        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="subscribers.csv"');
        $output = fopen('php://output', 'w');

        // Add CSV headers
        fputcsv($output, ['ID', 'Email', 'Subscribed At']);

        // Add subscriber data
        foreach ($subscribers as $subscriber) {
            fputcsv($output, [$subscriber->id, $subscriber->email, $subscriber->subscribed_at]);
        }

        fclose($output);
        exit;
    }
    

Conclusion

With this plugin, you can easily manage email subscriptions on your WordPress site. It:

  • Collects subscriber emails via a simple form.
  • Sends a confirmation email to subscribers after they subscribe.
  • Provides an option for admins to export subscriber data as a CSV file.

To install the plugin, simply upload the plugin folder to your WordPress wp-content/plugins directory and activate it from the WordPress admin.

This plugin provides a great foundation for email management and can be extended further for advanced functionality like integration with an email service provider or adding more customization options.

Let me know if you need any further assistance with your plugin!

Leave a Comment

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