All about the world of websites. Helpful guides and tipshow to create a professional website in a few steps

How to create a contact form in WordPress without plugins

How to create a contact form in WordPress without plugins

By daniele

WordPress is famous nowadays for being considered one of the most famous platforms for creating sites, thanks to a number of users that is around 28 million. The CMS is particularly famous for the ability to access an incredible number of plugins and extensions that are able to increase the performance and potential of the in-project web site. Many consider it the most convenient and fast solution even if, in reality, the plugins hide a whole series of pitfalls and problems that could emerge only at a later time. Plugins may be inefficient and slow down the site, not adapt itself to modules already installed, be hard to manage and also not so much customizable for each field. Fortunately, this is not the only solution if you want to create a contact form. It is possible to propose an alternative, maybe more functional and personalized, simply going to work on the HTML code of the page. Let’s see then how you can do it in a few simple steps. 

1- Create the page templates

The first step is about the creation of a page template that can be easily done by copying the page.php code into a new file named page-contact.php. If you want WordPress to treat the file as a page template, you will have to add a comment at the beginning of the contact.php.

  1. <?php

/*

Template Name: Contact

*/

?>

2- Build the form 

In general, the contact form includes a limited set of fields, specifically two input fields for the Full Name and Email of the user and a text-area for the Message of the user. You can, however, add or remove additional controls and CTA based on your specific needs.  

  1. <form id=”contact-form” action=”<?php echo esc_url( get_permalink() ); ?>”

    method=”post”>

 

    <input type=”hidden” name=”contact_form”>

 

    <div class=”form-section”>

        <label for=”full-name”><?php echo esc_html( ‘Full Name’, ‘twentytwentyone’ ); ?></label>

        <input type=”text” id=”full-name” name=”full_name”>

    </div>

 

    <div class=”form-section”>

        <label for=”email”><?php echo esc_html( ‘Email’, ‘twentytwentyone’ ); ?></label>

        <input type=”text” id=”email” name=”email”>

    </div>

 

    <div class=”form-section”>

        <label for=”message”><?php echo esc_html( ‘Message’, ‘twentytwentyone’ ); ?></label>

        <textarea id=”message” name=”message”></textarea>

    </div>

 

    <input type=”submit” id=”contact-form-submit” value=”<?php echo esc_attr( ‘Submit’, ‘twentytwentyone’ ); ?>”>

 

</form>

3- Verifying the data processing

The form now looks very good but could be very useless if before you don’t verify if the form has been submitted and if each field has been filled correctly. If fields are correctly filled, we’ll get the site admin email and send them the email. Otherwise, no email will be sent and errors will be displayed to the user. Only by copying the following code will you be able to make sure that the form has been submitted and filled correctly. If an error, such as an empty field or incorrect email address occurred, a message is returned and the form isn’t submitted.

  1. <?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;

}

 

} ?>

 

Otherwise the user will see an error message appear under the box that has not filled correctly:

  1. <?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 id=”container”>

<div id=”content”>

 

<?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=”entry-content”>

<?php if(isset($emailSent) && $emailSent == true) { ?>

<div class=”thanks”>

<p>Thanks, your email was sent successfully.</p>

</div>

<?php } else { ?>

<?php the_content(); ?>

<?php if(isset($hasError) || isset($captchaError)) { ?>

<p class=”error”>Sorry, an error occured.<p>

<?php } ?>

 

<form action=”<?php the_permalink(); ?>” id=”contactForm” method=”post”>

<ul class=”contactform”>

<li>

<label for=”contactName”>Name:</label>

<input type=”text” name=”contactName” id=”contactName” value=”<?php if(isset($_POST[‘contactName’])) echo $_POST[‘contactName’];?>” class=”required requiredField” />

<?php if($nameError != ”) { ?>

<span class=”error”><?=$nameError;?></span>

<?php } ?>

</li>

 

<li>

<label for=”email”>Email</label>

<input type=”text” name=”email” id=”email” value=”<?php if(isset($_POST[’email’]))  echo $_POST[’email’];?>” class=”required requiredField email” />

<?php if($emailError != ”) { ?>

<span class=”error”><?=$emailError;?></span>

<?php } ?>

</li>

 

<li><label for=”commentsText”>Message:</label>

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

<?php if($commentError != ”) { ?>

<span class=”error”><?=$commentError;?></span>

<?php } ?>

</li>

 

<li>

<input type=”submit”>Send email</input>

</li>

</ul>

<input type=”hidden” name=”submitted” id=”submitted” value=”true” />

</form>

<?php } ?>

</div><!– .entry-content –>

</div><!– .post –>

 

<?php endwhile; endif; ?>

</div><!– #content –>

</div><!– #container –>

 

<?php get_sidebar(); ?>

<?php get_footer(); ?>

  

4- Add jQuery verification

Now the form is perfect and you just need to add a client side verification using a simple jQuery plugin. The first thing to do is to download the validate plugin and upload it into your theme file (under a /js directory). Once done, paste the following into a new file:

  1. $(document).ready(function(){

$(“#contactForm”).validate();

});

Now it’s the time to link the javascript files to our theme. Open your header.php file and paste the following within the <head> and </head> tags:            

  1. <?php if( is_page(‘contact’) ){ ?>

<script type=”text/javascript” src=”<?php bloginfo(‘template_directory’); ?>/js/jquery.validate.min.js”></script>

<script type=”text/javascript” src=”<?php bloginfo(‘template_directory’); ?>/js/verif.js”></script>

<?php }?>

   

Syrus

Categorie

%d bloggers like this: