How to create a contact form in WordPress without plugins

11 March 2022
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.
- <?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. Â
- <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.
- <?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:
- <?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:
- $(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:Â Â Â Â Â Â Â Â Â Â Â Â
- <?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 }?>
  Â