Forms are an integral part of a website. While there are lots of wordpress plugins available to create custom forms, most of them are not up to the task. It is very easy to create a form in WordPress, provided you have a fair knowledge of php, html and js. Let me show you how it’s done.


Front-end [HTML]

> Open dashboard.

> Create a new page.

> Go to HTML mode.

> Create a form just like this:

<form action="../process.php" method="post" name="myForm">
Name <input id="name" type="text" name="name" />
Email <input id="email" type="text" name="email" />
<input type="submit" value="Submit" /></form>

> Specify the backend php script in the action attribute of the form tag. Include as many form fields as you wish. Specify the method of form submission as post.

> Publish the page.

Bravo! You have successfully completed the front end of the custom form.


Form Validation [JS]

> Include a javascript into the page which you’ve created.

> Add a script tag:

<script type="text/javascript">
/* JS validation code here */

> Create a validation function:

function validateForm()
/* Validating name field */
var x=document.forms["myForm"]["name"].value;
if (x==null || x=="")
 alert("Name must be filled out");
 return false;
/* Validating email field */
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
 alert("Not a valid e-mail address");
 return false;


Back-end [PHP]

> Create a new PHP file in your favourite text editor.

> Get the submitted form elements:

//get the form elements and store them in variables

> Connect to your database:

//establish connection
$con = mysqli_connect("Host","User name","Password","DB name"); 
//on connection failure, throw an error
if(!$con) {  
die('Could not connect: '.mysql_error()); 

> Insert the form values into the database:

$sql="INSERT INTO `DB name`.`Table name` ( `name` , `email_id` ) VALUES ( '$name','$email')"; 

> After the database is successfully updated, you need to redirect the user to a page with a success message(which I have assumed you have created via Dashboard). You can do this by,

//Redirects to the specified page
header("Location: http://your-success-page-url"); 

Now you have successfully created your php script which will be called in the action attribute. Upload this php file inside the wordpress directory.
NOTE: In the form action, I have used “../process.php” because the php file is one level above the page which contains the form.


Create a new page with a form successful submission message.
Make sure the URL of this page is the one which is specified in the header() of the php script.

That is it! You have successfully created a custom form and connected it with a database!