Javascript required
Skip to content Skip to sidebar Skip to footer

How to Create Form in Wordpress Without Plugin

Create contact form without plugin wordpress

screencapture localhost mysite contact 2020 06 28 20 25 13

There are plenty of plugins that can be used for adding almost any functionality to your WordPress powered site. However, if you're someone who likes to build things from the ground up, then probably you won't like to make use of the existing plugins.

You can deploy your stuff! When building something from scratch, you will understand the implementation of the underlying thing that you create, and can even learn skills that could end up using the same skills while working on another project

Contact form without plugin

  • Plugins can incorporate more features you really need.
  • Using a complex user interface to create a simple form and adding too many features is overkill.
  • Creating a plugin from the start will help you learn about what is under the hood, and you can use while working on another project.
  • Often plugins contain defective code that can eventually lead to bugs, which could either break your site or operates slowly.

Step 1: Create a contact page

  • Loing into yourwebsite admin panel(for eg. myside/wp-admin).
  • Go tothe page menu andadd a new page(contact).
  • Now publish that page.

Step 2: Create a custom template

Go towp-content/themes/yourtheme/and createcontact.phpfile

ensure WordPress will treat the file as a template page. For that, you can add code

<?php /* Template Name: Contact */ ?> This is a contact form          

if above code is working fine you can paste below code in contact.php

<?php /* Template Name: Contact */ ?>  <?php get_header() ?>   <div id="container">   <div id="content">    <?php the_post() ?>    <div id="post-<?php the_ID() ?>" class="post">     <div class="form-ares">     </div><!-- form-area -->    </div><!-- .post-->   </div><!-- #content -->  </div><!-- #container -->  <?php get_sidebar() ?> <?php get_footer() ?>          

Step 3: Build your required form

Now we need to create a simple contact form. Just paste the following code in the form-area div.

            <form action="<?php the_permalink(); ?>" id="contactForm" method="post">               <div class="col-xs-12">                 <div class="contactform">                   <div class="styled-input wide">                     <input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" class="required requiredField" />                     <label for="contactName">Name</label>                     <?php if($nameError != '') { ?>                       <span class="error"><?=$nameError;?></span>                     <?php } ?>                   </div>                 </div> 							</div>                <div class="col-xd-12">                   <div class="styled-input wide">                     <input type="text" name="email" id="email" value="<?php if(isset($_POST['email']))  echo $_POST['email'];?>" class="required requiredField email" />                     <label for="email">Email</label>                     <?php if($emailError != '') { ?>                       <span class="error"><?=$emailError;?></span>                     <?php } ?>                 </div> 							</div>                <div class="col-xs-12">                 <div class="styled-input wide">                     <textarea name="comments" id="commentsText" rows="20" cols="30" class="required requiredField"><?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?></textarea>                     <label for="commentsText">Message</label>                     <?php if($commentError != '') { ?>                       <span class="error"><?=$commentError;?></span>                     <?php } ?>                   </div> 							</div>                <div class="col-md-6 col-sm-12" style="float:right;">                   <input class="btn-lrg submit-btn" type="submit"></input> 						</div> 						<input type="hidden" name="submitted" id="submitted" value="true" /> 					</form>          

Nothing hard with this pretty explicit HTML code for our form. Note that the input type = "hidden" I added in line 37: It will be used later to check if the form was submitted.

Step 4: Error handling and data processing

Our form looks pretty good, but it is useless because it does not send an email. What we need to do is check if the form was submitted then check if the fields have been correctly filled.

If the fields are correct, we will have the admin email blog and send your message. Otherwise, no e-mail will be sent and errors will be displayed to the user.

Paste the following code between the page template declaration and get_header () function:

<?php if(isset($_POST['submitted'])) { 	if(trim($_POST['contactName']) === '') { 		$nameError = 'Please enter your name.'; 		$hasError = true; 	} else { 		$name = trim($_POST['contactName']); 	}  	if(trim($_POST['email']) === '')  { 		$emailError = 'Please enter your email address.'; 		$hasError = true; 	} else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST['email']))) { 		$emailError = 'You entered an invalid email address.'; 		$hasError = true; 	} else { 		$email = trim($_POST['email']); 	}  	if(trim($_POST['comments']) === '') { 		$commentError = 'Please enter a message.'; 		$hasError = true; 	} else { 		if(function_exists('stripslashes')) { 			$comments = stripslashes(trim($_POST['comments'])); 		} else { 			$comments = trim($_POST['comments']); 		} 	}  	if(!isset($hasError)) { 		$emailTo = get_option('tz_email'); 		if (!isset($emailTo) || ($emailTo == '') ){ 			$emailTo = get_option('admin_email'); 		} 		$subject = '[PHP Snippets] From '.$name; 		$body = "Name: $name \n\nEmail: $email \n\nComments: $comments"; 		$headers = 'From: '.$name.' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;  		wp_mail($emailTo, $subject, $body, $headers); 		$emailSent = true; 	}  } ?>          

What I did here was simply to ensure that the form has been submitted and filed properly. If an error, such as a blank or incorrect email address was held, a message is sent and the form is not submitted.

Now we have to display error messages below the related field, such as "Please enter your name." Below you will find the complete form page template that you can use "like".

<?php /* Template Name: Contact */ ?>  <?php if(isset($_POST['submitted'])) { 	if(trim($_POST['contactName']) === '') { 		$nameError = 'Please enter your name.'; 		$hasError = true; 	} else { 		$name = trim($_POST['contactName']); 	}  	if(trim($_POST['email']) === '')  { 		$emailError = 'Please enter your email address.'; 		$hasError = true; 	} else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST['email']))) { 		$emailError = 'You entered an invalid email address.'; 		$hasError = true; 	} else { 		$email = trim($_POST['email']); 	}  	if(trim($_POST['comments']) === '') { 		$commentError = 'Please enter a message.'; 		$hasError = true; 	} else { 		if(function_exists('stripslashes')) { 			$comments = stripslashes(trim($_POST['comments'])); 		} else { 			$comments = trim($_POST['comments']); 		} 	}  	if(!isset($hasError)) { 		$emailTo = get_option('tz_email'); 		if (!isset($emailTo) || ($emailTo == '') ){ 			$emailTo = get_option('admin_email'); 		} 		$subject = '[PHP Snippets] From '.$name; 		$body = "Name: $name \n\nEmail: $email \n\nComments: $comments"; 		$headers = 'From: '.$name.' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;  		wp_mail($emailTo, $subject, $body, $headers); 		$emailSent = true; 	}  } ?>  <?php get_header(); ?> 	<div class="container"> 			<?php if (have_posts()) : while (have_posts()) : the_post(); ?> 			<div <?php post_class() ?> id="post-<?php the_ID(); ?>"> 				<h1 class="entry-title"><?php the_title(); ?></h1> 					<div class="form-area"> 						<?php if(isset($emailSent) && $emailSent == true) { ?> 							<div class="thanks"> 								<p>Thanks, your email was sent successfully.</p> 							</div> 						<?php } else { ?> 							<?php the_content(); ?>X 							<?php if(isset($hasError) || isset($captchaError)) { ?> 								<p class="error">Sorry, an error occurred.<p> 							<?php } ?>            <div class="row input-container"> 						<form action="<?php the_permalink(); ?>" id="contactForm" method="post">               <div class="col-xs-12">                 <div class="contactform">                   <div class="styled-input wide">                     <input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" class="required requiredField" />                     <label for="contactName">Name</label>                     <?php if($nameError != '') { ?>                       <span class="error"><?=$nameError;?></span>                     <?php } ?>                   </div>                 </div> 							</div>                <div class="col-xd-12">                   <div class="styled-input wide">                     <input type="text" name="email" id="email" value="<?php if(isset($_POST['email']))  echo $_POST['email'];?>" class="required requiredField email" />                     <label for="email">Email</label>                     <?php if($emailError != '') { ?>                       <span class="error"><?=$emailError;?></span>                     <?php } ?>                 </div> 							</div>                <div class="col-xs-12">                 <div class="styled-input wide">                     <textarea name="comments" id="commentsText" rows="20" cols="30" class="required requiredField"><?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?></textarea>                     <label for="commentsText">Message</label>                     <?php if($commentError != '') { ?>                       <span class="error"><?=$commentError;?></span>                     <?php } ?>                   </div> 							</div>                <div class="col-md-6 col-sm-12" style="float:right;">                   <input class="btn-lrg submit-btn" type="submit"></input> 						</div> 						<input type="hidden" name="submitted" id="submitted" value="true" /> 					</form> 				<?php } ?> 				</div><!-- .form-area --> 			</div><!-- .post -->     </div>   				<?php endwhile; endif; ?> 	</div><!-- #container -->            <div class="container"> 	<div class="row"> 			<h1>contact us</h1> 	</div> 	<div class="row"> 			<h4 style="text-align:center">We'd love to hear from you!</h4> 	</div> 	<div class="row input-container"> 			<div class="col-xs-12"> 				<div class="styled-input wide"> 					<input type="text" required /> 					<label>Name</label>  				</div> 			</div> 			<div class="col-md-6 col-sm-12"> 				<div class="styled-input"> 					<input type="text" required /> 					<label>Email</label>  				</div> 			</div> 			<div class="col-md-6 col-sm-12"> 				<div class="styled-input" style="float:right;"> 					<input type="text" required /> 					<label>Phone Number</label>  				</div> 			</div> 			<div class="col-xs-12"> 				<div class="styled-input wide"> 					<textarea required></textarea> 					<label>Message</label> 				</div> 			</div> 			<div class="col-xs-12"> 				<div class="btn-lrg submit-btn">Send Message</div> 			</div> 	</div> </div>     <?php get_footer(); ?>          

Step 5: Adding jQuery verification

Our form is working perfectly. But we can improve by adding verification of the client-side. To do this, I'll use jQuery and jQuery validation plugin. This plugin is great because it allows you to verify that a form is filled out correctly, quickly and easily.

The first thing to do is download the plugin validation and upload your topic file (in the directory / js). Once done, paste the following into a new file:

$(document).ready(function(){ 	$("#contactForm").validate(); });          

Save it as anyname.js in your /js directory.

Now we have to link the javascript files to our theme. Open yourfunctions.php file and paste the following code:

wp_enqueue_script('themes-jquery-validate', get_template_directory_uri(). "/assets/js/jquery.validate.min.js" , array(), $version, true );          

Once done, the contact form will be validated on the side of the client by the jQuery validate plugin. How does it work? Simply collect form element with the CSS class requires and checks are filled correctly. If not, a message is displayed.

The plug-in is powerful and can do many things with it, however, this is not the purpose of this article. We hope you enjoy your new WordPress form!

How to Create Form in Wordpress Without Plugin

Source: https://www.wpdtech.com/create-contact-form-without-plugin-wordpress/