Explaining the Contact Us page

When you start a new website one of the key features is to have a contact page. Whether you have blog site, portfolio, shop or any kind of presentation you need to allow your visitors to contact you.

In this post I’ll explain some basic fields that are needed for one contact form as well as some of the techniques we use for validating this form.

Form on its own is really easy to create and set up but one always needs to protect himself from spammers, etc.

Let me start with basic HTML form contains just 3 fields: visitor’s name, email and message.

HTML code should look like this:

    <form method="POST" id="contactform" action="html_form.php" name="contactform" >
        <input type="text" name="contactname" id="contactname" tabindex="1" />
        <input type="text"  name="email" id="contactemail" tabindex="2" />
        <textarea name="contactmessage" id="contactmessage" tabindex="3"></textarea>
        <input type="submit" name="submit" value="Send Message" />
    </form>

Let me explain this a bit more.

Every object inside form is defined by name, id and type. Tabindex is just order of objects to be selected by pressing “TAB” key on keyboard.

Important thing is to have insert something unique for name and id. I like to call my objects by the page I’m using them,
in that case I don’t need to keep track in what file I am, but just looking at the form I know I’m working on contact form.

By inserting values in fields and pressing submit button contact page will refresh and we will have our form submitted.

Now you say OK, that’s cool what do I do with it?

The data that was submitted by form in not really visible by naked eye, you need to process the information you received by form.
To do this you need some PHP code that’s why I called my file “html_form.php”.

Every information from form is passed by POST method, this means that you’ll have $_POST variable filled with information form post.
This information is stored as array, which means that $_POST[‘nameofinput’] will have value that was submitted by form.

In my case that I’ll have 3 values: $_POST[‘contactname’], $_POST[‘contactemail’] and $_POST[‘contactmessage’].

Now that I have these values I need to send this contact to myself. I’ll use WordPress function for this called wp_mail().

You can find more info about this function here.

How do I do this? I just simply call function and pass the information I have like this:

    wp_mail( $to, $subject, $message, $headers, $attachments )

this is default usage of this function, but I’ll use my own information here like this:
    wp_mail( 'myemail@test.tst', 'This is e-mail from your test form', 'Someone named '.$_POST['contactname'].' from address '.$_POST['contactemail'].' sent you this message nnn'.$_POST['contactmessage']);

This is just basic contact form that will send information from inputs to e-mail address you enter.

Whole code should look something like this:

 <?php
     // PHP part
        if(isset($_POST)) {
            wp_mail( 'myemail@test.tst', 'This is e-mail from your test form', 'Someone named '.$_POST['contactname'].' from address '.$_POST['contactemail'].' sent you this message nnn'.$_POST['contactmessage']);
        } // end if form is posted

     ?>
    <!-- HTML part -->
    <form method="POST" id="contactform" action="html_form.php" name="contactform" >
        <input type="text" name="contactname" id="contactname" tabindex="1" />
        <input type="text"  name="email" id="contactemail" tabindex="2" />
        <textarea name="contactmessage" id="contactmessage" tabindex="3"></textarea>
        <input type="submit" name="submit" value="Send Message" />
    </form>

This is just base of every contact form, you never want to have something like this because there is no form validation.

Why is form validation so important? Well this form can send empty fields, and every bored person can click on submit button and spam your e-mail with empty messages.

There is two way of validating your form. First is to use PHP code to validate it or to use Javascript.
In our contact form (ThemesKingdom Themes) we use Javascript because that way you can validate your form before the form is actually submitted and in that case your page won’t be refreshed every time visitor make a mistake in form.

To explain how our contact form works I’ll use one of our themes.
The files I’ll be using are /themename/_contact.php and /themename/sendcontact.php

Firstly I’ll show you the whole code and then I’ll break everything step by step. Don’t be afraid if you see tons of letters.

<?php
    $subject_error_msg = get_option(tk_theme_name.'_contact_subject_error_message');
    $name_error_msg = get_option(tk_theme_name.'_contact_name_error_message');
    $email_error_msg = get_option(tk_theme_name.'_contact_email_error_message');
    $message_error_msg = get_option(tk_theme_name.'_contact_message_error_message');
    $mail_success_msg = get_option(tk_theme_name.'_contact_message_successful');
    $mail_error_msg = get_option(tk_theme_name.'_contact_message_unsuccessful');
    ?>

    <!-- Validate script -->
    <script type="text/javascript">
        function validate_email(field,alerttxt)
        {
            with (field)
            {
                apos=value.indexOf("@");
                dotpos=value.lastIndexOf(".");
                if (apos<1||dotpos-apos<2)
                {jQuery('#contact-error').empty().append(alerttxt);return false;}
                else {return true;}
            }
        }
        function check_field(field,alerttxt,checktext){
            with (field)
            {
                var checkfalse = 0;
                if(field.value == ""){
                    jQuery('#contact-error').empty().append(alerttxt);
                    field.focus();checkfalse=1;}

                if(field.value==checktext)
                {
                    jQuery('#contact-error').empty().append(alerttxt);
                    field.focus();checkfalse=1;}

                if(checkfalse==1){return false;}else{return true;}
            }
        }
        function checkForm(thisform)
        {
            with (thisform)
            {
                var error = 0;
                var contactmessage = document.getElementById('contactmessage');
                if(check_field(contactmessage,"<?php echo $message_error_msg?>","Message")==false){
                    error = 1;
                }
                var email = document.getElementById('contactemail');
                if (validate_email(email,"<?php echo $email_error_msg?>")==false)
                {email.focus();error = 1;}
                var contactname = document.getElementById('contactname');
                if(check_field(contactname,"<?php echo $name_error_msg?>","Name")==false){
                    error = 1;
                }
                if(error == 0){
                    var contactname = document.getElementById('contactname').value;
                    var email = document.getElementById('contactemail').value;
                    var contactmessage = document.getElementById('contactmessage').value;
                    return true;
                }
                return false;
            }
        }
    </script>
    <!-- end of script -->

        <!--FORM-->
        <div class="form left">
            <h2><?php _e('Say Hello', tk_theme_name)?></h2><!--/title-home-->
            <form method="POST" id="contactform" onsubmit="return checkForm(this)" action="<?php echo get_template_directory_uri().'/sendcontact.php'?>" >
                <div class="form-input left">
                    <div class="bg-input left"><input type="text" onfocus="if(value==defaultValue)value=''" onblur="if(value=='')value=defaultValue" value="<?php _e('Name', tk_theme_name)?>" name="contactname" id="contactname" tabindex="2"/><div class="down-border-form left"></div><!--/down-border-form--></div>
                    <div class="bg-input left"><input type="text" onfocus="if(value==defaultValue)value=''" onblur="if(value=='')value=defaultValue" value="<?php _e('E-mail', tk_theme_name)?>" name="email" id="contactemail" tabindex="3"/><div class="down-border-form left"></div><!--/down-border-form--></div>
                </div><!--/form-input-->
                <div class="form-textarea">
                    <textarea onfocus="if(value==defaultValue)value=''" onblur="if(value=='')value=defaultValue" name="message" id="contactmessage" tabindex="4"><?php _e('Message', tk_theme_name)?></textarea><div class="down-border-form left"></div><!--/down-border-form-->
                </div><!--/form-textarea-->
                <div class="form-submit-button left"><input class="search-submit-button" type="submit" name="submit" value="<?php _e('Send', tk_theme_name)?>" /></div>
                <input type="hidden" name="returnurl" value="<?php echo get_permalink();  ?>">
                <div id="contact-success"><?php if(isset($_GET['sent'])) {
                        $what = $_GET['sent'];
                        if($what == 'success') {
                            echo $mail_success_msg;
                        }
                    }
                    ?></div>
                <div id="contact-error"><?php if(isset($_GET['sent'])) {
                        $what = $_GET['sent'];
                        if($what == 'error') {
                            echo $mail_error_msg;
                        }
                    }
                    ?></div>
        </div><!--/form-button-->
        </form>
    </div><!--/form-->

OK, so from the very start I pick up some values from theme panel. These are used if visitor makes a mistake in contact form to inform him what kind of error occurred.
These values could also be any kind of text, just insert them as string like this:
    $name_error_msg = 'You made mistake in name field.';

Second part is where I use javascript just to check if fields are empty or in case they have predefined value that new value is actually inserted.
This is check_field function.

Also I use validate_email function to check if proper e-mail address is inserted. That means that value of e-mail field has one “@” sign, and 3 letters after “.” (dot).

To add another field to this check simply call check_field function for that field like this:

    var some_variable_name = document.getElementById('field_name');
    if(check_field(some_variable_name,"This is text message that informs that field is empty.","")==false){
        error = 1;
    }

and add field to this if statement:
    if(error == 0){
        var contactname = document.getElementById('contactname').value;
        var email = document.getElementById('contactemail').value;
        var contactmessage = document.getElementById('contactmessage').value;
        var some_variable_name = document.getElementById('field_name').value;
    return true;
    }

Although HTML code for form looks a lot bigger it’s the same as first example. There are some objects added in order to answer designers request.
This part:
    onfocus="if(value==defaultValue)value=''" onblur="if(value=='')value=defaultValue" value="<?php _e('Name', tk_theme_name)?>"

is added to inputs so that default value of input is “Name” and when visitor starts to enter his own information (either with mouse click or Tab key on keyboard) he’ll have empty field to insert information.

Again to add another field to this form simply add something like this:

    <div class="bg-input left"><input type="text" onfocus="if(value==defaultValue)value=''" onblur="if(value=='')value=defaultValue" value="<?php _e('Either empty or default text', tk_theme_name)?>" name="field_name" id="field_name" tabindex="4"/><div class="down-border-form left"></div></div>

Next file is /themename/sendcontact.php. This part is the one that actually sends e-mail and in case of an error returns the error to contact page without refreshing that page.
    $to = get_option('admin_email');                  //Enter your email here.
    $subject =  get_theme_option(tk_theme_name.'_contact_contact_subject');
    $from = $_POST['contactname'];
    $name = $_POST['email'];
    $message = $_POST['message'];
    $headers = "From: $name <$from>n";
    $headers .= "Reply-To: $subject <$from>n";
    $return = $_POST['returnurl'];
    $sitename =get_bloginfo('name');
    $body = "You received e-mail from ".$from."  [".$name."] "." using ".$sitename."nnn".$message;
    $send = wp_mail($to, $subject, $body, $headers) ;
    if($send){
        wp_redirect($return.'?sent=success');
    }else{
        wp_redirect($return.'?sent=error');
    }

This part doesn’t need much explanation. I just gather all information from contact form and send email to WordPress administrator.

To include information from another field like in HTML example just add another variable like this:

    $field_name = $_POST['field_name'];

and add it somewhere in email. For example this information is visitor last name, then you add this to $body variable:
    $body = "You received e-mail from ".$from."  [".$name."] [".$field_name."] "." using ".$sitename."nnn".$message;

Because this kind of contact form is easy to abuse it’s really important to use some sort of protection from spam messages.
Easiest option is to use some sort of “captcha” to prevent robots from spamming your email address.

Next time I’ll try to explain a bit more how to insert captcha field to this form, and explain how most common captcha generators work as well as some good captcha plugins that I find.

Leave a Reply

Your email address will not be published. Required fields are marked *