In this WordPress tutorial, you’ll learn how to build a newsletter form in WordPress without using a plugin. This method can also be applied to create other custom forms such as contact forms, feedback forms, appointment and booking forms, survey forms, and payment forms.

Write Code in functions.php

First, we’ll create a child theme to ensure that our code remains intact during theme updates. In this tutorial, we’ll add our subscription form code to the functions.php file of the child theme.

Create a Database Table

Next, we need to create a table in our database. We’ll create a table named $wpdb->prefix . 'subscribers' with three columns:

  • id: This column will be set to auto-increment.
  • subscribers_email: Stores the subscriber’s email address.
  • date_of_subscription: It will have a default value of the current timestamp.

Here’s an example of how the table might look:

idsubscribers_emaildate_of_subscription
1admin@diversifyindia.in10-12-2023
2contact@diversifyindia.in03-05-2024
Table for storing subscribers data

Automatically Generate Tables

Instead of manually creating the database tables, you can automate this process using the dbDelta function.

function create_newsletter_table() {
    global $wpdb;

    // get charset from wpdb class
    $charset_collate = $wpdb->get_charset_collate();

    // sql command to create database table
    $sql = "CREATE TABLE {$wpdb->prefix}subscribers (
        id int(20) NOT NULL auto_increment,
        subscribers_email varchar(2048),
        date_of_subscription timestamp default CURRENT_TIMESTAMP,
        PRIMARY KEY  (id)
    ) {$charset_collate};";

    // include upgrade.php file to use dbDelta function
    if( ! function_exists('dbDelta') ) {
        include_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
    }

    dbDelta( $sql );
}

// attach this function to 'init' hook
add_action( 'init', 'create_newsletter_table' );

Create a Shortcode

The next step is to create a shortcode for our form. To do this, use the add_shortcode function in WordPress. The first argument of this function is the name of your shortcode, and the second argument is the name of the callback function that will handle the shortcode’s output.

add_shortcode('newsletter-form', 'newsletter_handler');

Shortcodes in WordPress allow developers to insert snippets of code into posts, pages, and widgets. This feature is highly versatile and can be used to create a variety of elements, including forms, online games, and applications such as Sudoku, Color Converter, HTML Cleaner, and more.

Define the Callback Function

Define the callback function for your shortcode. This function will generate and return the HTML form that appears on your site.

function newsletter_handler() {
    $html = '<form method="post" action="#" style="margin-bottom: 16px;">' .
    '<div style="margin-bottom: 16px;">' .
        '<label for="email" style="margin-right: 16px;">Email</label>' .
        '<input id="email" type="email" name="email">' .
    '</div>' .
    '<div>' .
        '<button type="submit" name="submit">Subscribe</button>' .
    '</div></form>';
    return $html;
}

Handle Form Data

Here’s how you can handle form data submitted by visitors in the same file using the newsletter_handler method defined in the previous step:

function newsletter_handler() {
    // use global database object to store data in our database
    global $wpdb;

    // Check if form has been submitted
    if(isset($_POST["submit"])) {

        // use insert method of wpdb class to insert data in database
        $wpdb->insert(
            $wpdb->prefix . 'subscribers',
            array(
                'subscribers_email' => $_POST["email"]
            )
        );
        return "<div style='text-align: center;'>Successfully subscribed.</div>";
    }

    $html = '<form method="post" action="#" style="margin-bottom: 16px;">' .
    '<div style="margin-bottom: 16px;">' .
        '<label for="email" style="margin-right: 16px;">Email</label>' .
        '<input id="email" type="email" name="email">' .
    '</div>' .
    '<div>' .
        '<button type="submit" name="submit">Subscribe</button>' .
    '</div></form>';
    return $html;
}

You can further enhance this by adding error checks and using WordPress nonce for security against CSRF attacks.

Use the Shortcode

To display the form on your site, simply add the shortcode [newsletter-form] to any post or page where you want the form to appear.

Complete Code

Here is the complete code for creating a newsletter form in WordPress:

function create_newsletter_table() {
    global $wpdb;

    // get charset from wpdb class
    $charset_collate = $wpdb->get_charset_collate();

    // sql command to create database table
    $sql = "CREATE TABLE {$wpdb->prefix}subscribers (
        id int(20) NOT NULL auto_increment,
        subscribers_email varchar(2048),
        date_of_subscription timestamp default CURRENT_TIMESTAMP,
        PRIMARY KEY  (id)
    ) {$charset_collate};";

    // include upgrade.php file to use dbDelta function
    if( ! function_exists('dbDelta') ) {
        include_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
    }

    dbDelta( $sql );
}

// attach this function to 'init' hook
add_action( 'init', 'create_newsletter_table' );

function newsletter_handler() {
    // use global database object to store data in our database
    global $wpdb;

    if(isset($_POST["submit"])) {

        // use insert method of wpdb class to insert data in database
        $wpdb->insert(
            $wpdb->prefix . 'subscribers',
            array(
                'subscribers_email' => $_POST["email"]
            )
        );
        return "<div style='text-align: center;'>Successfully subscribed.</div>";
    }

    $html = '<form method="post" action="#" style="margin-bottom: 16px;">' .
    '<div style="margin-bottom: 16px;">' .
        '<label for="email" style="margin-right: 16px;">Email</label>' .
        '<input id="email" type="email" name="email">' .
    '</div>' .
    '<div>' .
        '<button type="submit" name="submit">Subscribe</button>' .
    '</div></form>';
    return $html;
}

add_shortcode('newsletter-form', 'newsletter_handler');

To display the data collected by this WordPress form on the backend of your website, you can use the WP_List_Table class. For detailed instructions, you can read our article on how to implement a list table using the WP_List_Table class.

Using Plugins for Form Creation

There are many plugins available for creating forms in WordPress. Here’s a list of popular ones:

  • Contact Form 7: It is a lightweight, completely free plugin with no advertisements or jQuery on the frontend. It offers database support through the lightweight Flamingo plugin. Recommended by Diversify India.
  • Forminator: It is a heavy plugin that uses jQuery, includes advertisements, and has built-in database support. It is a freemium plugin recommended for freelancers.
  • Ninja Forms: It is a heavier plugin that includes advertisements, uses jQuery, and has built-in database support. It is a freemium plugin.
  • Contact Form by WPForms: A very heavy plugin that uses jQuery and has many advertisements. It is a freemium plugin.

To learn about the most useful WordPress plugins, you can read our article on the must-have WordPress plugins.

Database support is crucial to ensure you don’t lose important messages if your mail server encounters issues or if there’s an error in your mail configuration. Therefore, it’s highly recommended to install the Flamingo plugin when using Contact Form 7. Both plugins are developed by the same author and are very lightweight. If you need assistance for setting up an SMTP server, you can read our article on configuring SMTP for a WordPress website.

Frequently Asked Questions

How do I use custom CSS with Contact Form 7?

To add custom CSS for Contact Form 7, you can create a separate CSS file and target the following CSS classes:

/* Design the Contact Form 7 container */
.wpcf7-form {
    background-color: #ff0;
}
/* Design input boxes */
.wpcf7-form input {
    font-size: 24px;
}
/* Design the submit button */
.wpcf7-form input[type="submit"] {
    padding: 5px;
}

After creating your custom CSS, enqueue this CSS file using the wp_enqueue_scripts hook:

function cf7_css() {
    wp_enqueue_style('style-name', get_template_directory_uri() . '/css/cf7.css', array(), 1.0, 'all');
}
add_action( 'wp_enqueue_scripts', 'cf7_css' );

Which is the best plugin to create forms in WordPress?

Contact Form 7 is considered the best plugin for creating forms in WordPress because it is lightweight, easy to set up, and consumes fewer resources compared to other contact form plugins.

Is it good to use plugins for creating forms in WordPress?

For personal websites that require only one or two simple forms, such as a contact or newsletter form, it’s not necessary to install a dedicated plugin. However, for more complex forms or for client websites, using a plugin is a good idea.

What is honeypot protection?

Honeypot protection is a security mechanism that creates traps to lure cyber attackers. In the context of forms, Honeypot Form Protection involves creating additional form fields that are hidden from regular users but visible to bots. If these hidden fields are filled out, the form data can be safely discarded, as it is likely submitted by a bot.