How to create custom forms in WordPress without using plugins?

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.

STEP #1

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.

STEP #2

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 */
...
...
</script>

> 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;
 }
}

STEP #3

Back-end [PHP]

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

> Get the submitted form elements:

<?php 
//get the form elements and store them in variables
$name=$_POST["name"]; 
$email=$_POST["email"]; 
?>

> Connect to your database:

<?php 
//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:


<?php 
$sql="INSERT INTO `DB name`.`Table name` ( `name` , `email_id` ) VALUES ( '$name','$email')"; 
mysqli_query($con,$sql); 
?>

> 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,


<?php
//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.

STEP #4

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!

About these ads

10 thoughts on “How to create custom forms in WordPress without using plugins?

  1. Thank you very much, I was puzzling over how to pass $_POST vars with pretty permalinks and your post made it easy! Next thing to figure out, how to pass some vars to the “thank you” page for customized response…

    • Joe – did you figure out how to pass your vars to the thank you page ? That’s something I’m struggling with also. I can obviously echo them (with HTML tags around them) within the form handler but then I have to somehow make the form handler display a properly formatted page. Not having any luck with that.

      Any tips would be appreciated !

      • One possible solution which I could think of is this: You can POST the variables in header and get them on your thank you page. Of course, WP doesn’t allow you to execute PHP in those pages. So you can either create a custom page template (recommended) or install any one of the plugins which enables PHP in WP pages.

    • I have not tried this but I suppose you can pass the variables using POST method.
      Example:
      header(‘location: url/?variable=’ . urlencode($_POST[‘var_name’]));
      The urlencode() function takes care of any reserved characters in the url.

      • Thanks so much for the quick response ! What I’m actually trying to accomplish is this:
        #1) I have small form in a WordPress page template – just below the content and above the footer. There is no real room here to show javascript error messages so I want to have the form’s action point to another page (call that #2) that I would use as a form handler.
        #2) I created another template with a form handler in it to validate all of the $_POST variables — and then display both errors and the form if corrections were needed, or a “Thankyou” if they were not needed. I created a WordPress page using this template (this page uses itself for the form’s “action”). However, when I hit submit (on the page discussed in #1), my debugging echos (from the handler in page #2) show me that none of the $_POST variables are set in the handler. So apparently they are not passed from one WordPress page (#1) to the other (#2).

        I think you are suggesting that I bypass the standard form “Submit” and send all of the $_POST variables using the header function.

        I’ll try that next ! Thanks again.

    • Shibu – obviously you’re right. And I may have to settle for that. But (since this is my site and not a client’s) I thought it might be a good opportunity to learn a bit more about WordPress. If I make any progress, I’ll let you know :-)

  2. Thank you for these instructions. I have existing HTML forms that I want to use “as is” on a WP static site, and this was just the ticket. I don’t want to put my form results into the database, though; I want to send them in an e-mail. Is there anything special I need to do to work with e-mailing results out of WP vs. e-mailing them on a regular HTML/CSS site?

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s