Custom form in WordPress without plugin

WordPress-Logo

There are multiple plugins to build and integrate custom forms in WordPress. Some plugins provide limited functionality and customization options while some premium plugins provide more customization options. If the form requirements are fulfilled by those plugins and don’t want to spend much time in coding, its best to use it to saves time. But if you are looking forward for customized solution and ready to invest some time, you can build your own custom form in wordpress, which you can customize as per the requirement.

Here we will create a simple contact form and save to database.

Custom Form Template

We will start by creating a page template in our custom theme directory. Here we will create a contact form page template called contact_page_template.php and add out contact form in this template.

// contact_page_template.php
<?php 
/* 
 * Template Name: Contact Form 
 * Template Post Type: page 
 */ 
 
get_header(); 
?> 
 
<div> 
    .. content before contact form 
</div> 
<!-- Form section -->
<div id="contact-form"> 
    <form action="<?php echo esc_url(admin_url('admin-post.php')); ?>" method="post" name="custom_contact_form"> 
        <div> 
            <label for="fullname"> 
                Full Name: 
            </label> 
            <input type="text" name="fullname" id="fullname" required /> 
        </div> 
        <div> 
            <label for="email"> 
                Email: 
            </label> 
            <input type="email" name="email" id="email" required /> 
        </div> 
        <div> 
            <label for="message"> 
                Message: 
            </label> 
            <textarea name="message" id="message" required></textarea> 
        </div> 
 
        <!-- pass admin method to handle form post -->
        <input type="hidden" name="action" value="custom_contact_form"> 
 
        <button type="submit" name="send_message"> 
            Send 
        </button> 
 
    </form> 
</div> 
<!-- End of Form section -->
<div> 
    .. content after contact form 
</div> 
 
<?php get_footer(); ?>

Our contact page template is ready. Now, we will create new contact page in wordpress admin, or edit one if already created. And in page attributes section, select page template as “Contact Form”. You can view our custom contact form by visiting contact page url.

Handle form post

We have our custom form ready. Now we need to handle form submission and save submitted form data to database. We will add form submit handling methods in functions.php file of our custom theme. To keep my functions.php file clean, I’m adding form handling methods in new file called custom_contact.php and include it in my functions.php. Here, we will bind handle_custom_contact_form() method to admin post action which will call this method on form submission. You can learn more about admin_post_action hook here. In handle_custom_contact_form() method, we will check database if table required to save form data exists. If not, we will create that table and proceed to save form data. And will redirect to different pages based of success or failure to save form data.

// custom_contact.php
<?php
add_action('admin_post_nopriv_custom_contact_form', 'handle_custom_contact_form'); //for non logged in users
add_action('admin_post_custom_contact_form', 'handle_custom_contact_form'); // for logged in users

function handle_custom_contact_form()
{
    global $wpdb;
    $params = $_POST;
    $table_name = $wpdb->prefix . 'contact_requests';
    $query = $wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->esc_like($table_name));
    if (!$wpdb->get_var($query) == $table_name) {
        /*create table if not exists*/
        $sql = "CREATE TABLE {$table_name} (
            id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            full_name VARCHAR(255) NOT NULL,
            email VARCHAR(255) NOT NULL,
            message_detail TEXT NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        )";
        if (!$wpdb->query($sql))
            die('Failed to create table');
    }

    if (save_to_DB($table_name, $params)) {
        wp_redirect('PAGE_URL_TO_REDIRECT_ON_SUCCESS');
    } else
        wp_redirect('PAGE_URL_TO_REDIRECT_ON_ERROR');
}

function save_to_DB($table_name, $params)
{
    global $wpdb;
    $query = "INSERT INTO {$table_name}(full_name, email, message_detail) 
    VALUES('{$params['full_name']}','{$params['email']}','{$params['message']}')";
    return $wpdb->query($query);
}

Include custom_contact.php to our custom theme’s functions.php

<?php
... other methods and actions in function.php

include(custom_contact.php);

Now we are ready to submit our custom contact form and add to database records. You can also extend our form post handling method “handle_custom_contact_form()” method to send email notification on form submit.

Mail notification

For email notification, we will use wordpress wp_mail() method. This is our mail notification method that is called on form submission success.

function send_mail_notification($message)
{
    $from_name = get_option('blogname');
    $subject = "Message from User";
    $to = "[email protected]";
    $headers[] = 'Content-Type: text/html; charset=UTF-8';
    $headers[] = "From: $from_name <[email protected]>";

    wp_mail($to, $subject, $message, $headers);
}

Let’s update our “handle_custom_contact_form()” method in custom_contact.php to send email notification for each successful form submit.

function handle_custom_contact_form()
{
    global $wpdb;
    $params = $_POST;
    $table_name = $wpdb->prefix . 'contact_requests';
    $query = $wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->esc_like($table_name));
    if (!$wpdb->get_var($query) == $table_name) {
        /*create table if not exists*/
        $sql = "CREATE TABLE {$table_name} (
            id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            full_name VARCHAR(255) NOT NULL,
            email VARCHAR(255) NOT NULL,
            message_detail TEXT NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        )";
        if (!$wpdb->query($sql))
            die('Failed to create table');
    }

    if (save_to_DB($table_name, $params)) {
        send_mail_notification($params); // call mail notification method
        wp_redirect('PAGE_URL_TO_REDIRECT_ON_SUCCESS');
    } else
        wp_redirect('PAGE_URL_TO_REDIRECT_ON_ERROR');
}

After adding mail notification method call on successful form submission and save to DB, we are ready to receive messages from our custom wordpress form and receive email notification for each successful submission.

We can use this method to create custom forms for different purpose like product inquiry form, news letter subscription, etc.

You May Also Like