Build a HTML Form From Scratch and Use in WordPress Post/Pages

You have many plugin to use form in your post/pages and they can do great job for you. but what about creating a simple form by own-self from scratch and use that in your posts?

so lets start with simple coding style and create a form with three field

<form action="" method="post" enctype="multipart/form-data" name="form" >
<label for="yourname"></label>
<input type="text"  id="yourname" name="yourname">

<label for="gender"></label>
<select id="gender" name="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>

<label for="address"></label>
<input type="text"  id="address" name="address">

<input  type="submit" name="submit" value="submit">

this is a simple form to use in html page but not for WordPress. WordPress has its on ways.

to use this form in some post or page you need to create a page template or use shorcode to display form. page template are great way to go but in this case i am suggesting you to use wp shortcode.

So just move to your WordPress template directory and  open functions.php file

and place this short code there.

function createform() {
// your form code

}

add_shortcode('form', 'createform');

shortcode made our job so simple, now you can use [form ] to place everywhere in post/page. just put [form] in your posts and this will fetch code inside createform(); function.

so now put code in function

function createform() {
return '
<pre><div id="forms">
<form action="" method="post" enctype="multipart/form-data" name="form" >
<label for="yourname"></label>
<input type="text"  id="yourname" name="yourname">

<label for="gender"></label>
<select id="gender" name="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>

<label for="address"></label>
<input type="text"  id="address" name="address">

<input  type="submit" name="submit" value="submit"></pre>
';

 }

add_shortcode('form', 'createform');

now create an new post and put [form] in your post , you must be able to see our created form there.

for next step to move we need to be able to submit this form. now again open up your functions.php file and put this code.

add_action('init', 'submit');

function submit(){
if(isset($_POST['submit']))
{
$myname=$_POST['myname'];
$gender=$_POST['gender'];
$address=$_POST['address'];
$sql=INSERT INTO form (id, myname, gender, address) VALUES
('', '$myname', '$gender','$address', );

&quot;;

require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);

}
}

and you are done!