How To Add Custom Contact Form And Popup In Wordpress

Getting Started

In this tutorial, we'll integrate custom wordpress contact form and popup

Note: You can click below link to install wordpress.

Install Worpress 5 On Lamp Stack Ubuntu 18 

Integrate Contact Form

Open your wordpress URL and enter your credentials to login.

wordpress login

Next, Go to appearance and select widget

Wordpress Appearance

Next, In custom HTML, select sidebar and click add a widget. A Custom HTML input field will appear

Wordpress add widget

 

<form class="form-control" action="../contact-form.php" method="POST" id="contact-form-js" name="contact_form" style="text-align: left;">
    <div>Fields marked with an * are required</div>
    <div class="form-group">
        <label for="name">Name *</label>
        <br>
        <input id="name" class="form-control" name="name" type="text" placeholder="Full Name" />
    </div>
    <br>
    <div class="form-group">
        <label for="email">Email address *</label>
        <br>
        <input id="email" class="form-control" name="email" type="email" placeholder="Enter email" aria-describedby="emailHelp" />
        <br>
    </div>
    <br>
    <div class="form-group">
        <label for="phone">Phone *</label>
        <br>
        <input id="phone" class="form-control" type="text" name="phone" placeholder="Phone Number" />
    </div>
    <br>
    <div class="form-group">
        <label for="message">Message *</label>
        <br>
        <textarea class="form-control" name="message" id="message"></textarea>
    </div>
    <br>
    <div>
        <button class="btn btn-default" type="button" value="Submit" id="contact-btn">Submit</button>
    </div>
</form>

Next, Copy the above code and paste it into the custom HTML input field. Put the title name then click done and save.

wordpress contact form html php code

Next, Drag and drop the custom HTML according to your need. I have dragged to the top.

wordpress form drag and drop

Open the wordpress URL in the next tab. You'll find the following screen with contact us form.

wordpress contact form success page

 

 

Validate the form with jquery and make ajax request

Now the HTML contact form has been implemented. Time to validate the form and make ajax call to save the form data.

To do so, Copy and paste the below code at the end of the file. You can find jquery file in 

wp-includes/js/jquery/jquery.js

jQuery(document).ready(function() {
	// Custom From submistion
jQuery(function($) {
        $('#contact-btn').click(function(){
        var name = document.forms["contact-form-js"]["name"].value;
        if (name == "" || name == null) {
            alert("Name field must be filled!");
            return false;
        }
        var email = document.forms["contact-form-js"]["email"].value;
        var at_position = email.indexOf("@");
        var dot_position = email.lastIndexOf(".");
        if (at_position<1 || dot_position<at_position+2 || dot_position+2>=email.length) {
            alert("Given email address is not valid.");
            return false;
        }
        var phone = document.forms["contact-form-js"]["phone"].value;
        if (phone == "" || phone == null) {
             if(!isNaN(phone)){
                alert("Please enter correct phone number.");
             }
            return false;
        }
        var message = document.forms["contact-form-js"]["message"].value;
        if (message == "" || message == null) {
            alert("Please type message.");
            return false;
        }
        $('#contact-btn').prop('disabled', true);
        var data = $('#contact-form-js').serialize();
        var url = window.location.href;
        data += "&url=" + url;
        var originUrl = window.location.origin;

        $.ajax({
            url: originUrl + "/contact-form.php",
            type: "POST",
            data: data,
            complete: function (json) {
            	console.log(json);
                var jsonData = $.parseJSON(json.responseText);
                if (jsonData['msg'] == 'success') {
                    alert('success');
                    $("#contact-form-js").hide();
                } else {
                    alert("Sorry! Something went wrong. Please try again.");
                }
            }
        });

    });
  
  // popup form
  $('#contact-popup-btn').click(function(){
        var name = document.forms["contact-form-popup-js"]["name"].value;
        if (name == "" || name == null) {
            alert("Name field must be filled!");
            return false;
        }
        var email = document.forms["contact-form-popup-js"]["email"].value;
        var at_position = email.indexOf("@");
        var dot_position = email.lastIndexOf(".");
        if (at_position<1 || dot_position<at_position+2 || dot_position+2>=email.length) {
            alert("Given email address is not valid.");
            return false;
        }
        var phone = document.forms["contact-form-popup-js"]["phone"].value;
        if (phone == "" || phone == null) {
             if(!isNaN(phone)){
                alert("Please enter correct phone number.");
             }
            return false;
        }
        var state = document.forms["contact-form-popup-js"]["message"].value;
        if (message == null) {
            alert("Please enter message.");
            return false;
        }

        $('#contact-popup-btn').prop('disabled', true);
        var data = $('#contact-form-popup-js').serialize();
        var url = window.location.href;
        data += "&url=" + url;
        var originUrl = window.location.origin;
        
        $.ajax({
            url: originUrl + "/contact-form.php",
            type: "POST",
            data: data,
            complete: function (json) {
                var jsonData = $.parseJSON(json.responseText);
                if (jsonData['msg'] == 'success') {
                	console.log('ajaax');
                	// To get the popup maker id you can inspect the popup form and get the di
                    jQuery('#popmake-11').popmake('close');
                } else {
                    alert("Sorry! Something went wrong. Please try again.");
                }
            }
        });

    }); 
  });
});

Note: I have added the Popup Maker code. we'll be adding the popup form after the sidebar contact form is done.

The Server Side PHP Code

Next, Create a new file contact-form.php in the root directory of wordpress and paste the below code

# contact-form.php

<?php
// Get data
$name = reString($_POST["name"]);
$email = reString($_POST["email"]);
$phone = reString($_POST["phone"]);
$message = reString($_POST["message"]);
$url = $_POST["url"];

// Database connection
require_once('wp-config.php');
if ( 'POST' != $_SERVER['REQUEST_METHOD'] ) {
	$protocol = $_SERVER['SERVER_PROTOCOL'];
	if ( ! in_array( $protocol, array( 'HTTP/1.1', 'HTTP/2', 'HTTP/2.0' ) ) ) {
		$protocol = 'HTTP/1.0';
	}
	header('Allow: POST');
	header("$protocol 405 Method Not Allowed");
	header('Content-Type: text/plain');
	exit;
} else {
	if ($name != NULL && $email != NULL && $phone != NULL && $message != NULL ){
		// Database connection
		$conn = mysqli_connect('localhost', 'root', 'root', 'blog');
		if(!$conn) {
			die('Problem in database connection: ' . mysql_error());
		}

		// date_default_timezone_set("Asia/Kolkata");
	    $new_date = new DateTime();
	    $new_date->setTimeZone(new DateTimeZone('Asia/Kolkata'));
	    $created_at =  $new_date->format("Y-m-d h:i:s");
		$query = "INSERT INTO `blog`.`wp_contact_form` (name, email, phone, message, url, created_at) VALUES ('$name', '$email', '$phone', '$message', '$url', '$created_at')";

		$query_load = mysqli_query($conn, $query);

		if ($query_load) {
			$output = array(
			    "msg" => "success",
			);
		} else {
			$output = array(
			    "error" => "internal server error",
			);
		}
	} else {
		$output = array(
		    "msg" => "please enter valid input.",
		);
	}
	echo json_encode($output);
}
function reString($input) {
	return filter_var($input, FILTER_SANITIZE_STRING);
}
?>

Note: I have added one additional field URL to track on which URL user has submitted the contact form.

Create a new table into the database

Next, add the contact form table into the database. Login to your MySQL, Select the database and paste the below query.

CREATE TABLE `wp_contact_form` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) DEFAULT NULL,
  `email` varchar(45) DEFAULT NULL,
  `phone` varchar(45) DEFAULT NULL,
  `message` text,
  `url` varchar(100) DEFAULT NULL,
  `created_at` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

 All done. now test the form.

 

Integrate PopUp Form

To integrate popup form we need to install Popup Maker plugins. To install Go to the plugins menu and select add new and search for Popup Maker.

wordpress popup maker plugins install

 Now click install and then activate.

Note: If you get to enter FTP connection information. You can disable by adding below code to wp_config.php

define('FS_METHOD', 'direct');

 

Wordpress disable wordpress FTP Connection

Once you activate, The Popup Maker menu will appear in the sidebar menu. Next select add popup link from the popup maker menu. The following screen will appear.

Wordpress Popup maker contact form

Next, select the text tab and paste the below code.

<form class="form-control" action="../contact-form.php" method="POST" id="contact-form-popup-js" name="contact_form" style="text-align: left;">
    <div>Fields marked with an * are required</div>
    <div class="form-group">
        <label for="name">Name *</label>
        <br>
        <input id="name" class="form-control" name="name" type="text" placeholder="Full Name" />
    </div>
    <br>
    <div class="form-group">
        <label for="email">Email address *</label>
        <br>
        <input id="email" class="form-control" name="email" type="email" placeholder="Enter email" aria-describedby="emailHelp" />
        <br>
    </div>
    <br>
    <div class="form-group">
        <label for="phone">Phone *</label>
        <br>
        <input id="phone" class="form-control" type="text" name="phone" placeholder="Phone Number" />
    </div>
    <br>
    <div class="form-group">
        <label for="message">Message *</label>
        <br>
        <textarea class="form-control" name="message" id="message"></textarea>
    </div>
    <br>
    <div>
        <button class="btn btn-default" type="button" value="Submit" id="contact-popup-btn">Submit</button>
    </div>
</form>

Next, Add the trigger to Auto Open Form and set the cookie on close.

Wordpress Popup maker cookie set form Click add, And in the next screen, it will ask to add time delay settings. set the time and click Add.

Wordpress Popupmaker cookie

 Next, Select the Popup theme from the display tab.

Wordpress popup maker theme select

 Open the wordpress homepage URL in the next tab. The Popup form will appear after some time.

Test the form and done.

Note: If you get any error or can't submit the form. Make sure you have added the correct popup maker form id to Jquery file as mentioned above. Read the comment in the jquery file.

Also, To get the popup maker id you can inspect the popup maker form and copy the id.