smart search

WordPress Custom Ajax Contact Form

Written by me@grafxflow -
30 Apr, 2017

Most people are aware of the plugins for WordPress that help you create forms - Contact Form 7 and Ninja Forms etc. But what about building your own custom ajax contact form using the admin-ajax WordPress functions. Well here is a starter tutorial which I have created where I am guessing you already know the basics of how to create custom themes and pages in WordPress.

For this example I will be using the following extras (Note: none are WordPress plugins):

BootstrapValidator for the form validation + this also includes jQuery 1.11.1 Download

NOTE: I have tried to add notes to the code examples as a more detailed breakdown. I have also added the CSS inside the page, but best practise would be to add them to the themes style.css file.

Step 1:

Create the custom WordPress theme contact page

So first let's create a custom page template for the contact page. Given the below details at the start of the file it will allow us to create a contact page and select this as a custom template. As for the form I am creating the following items all of which will be required - Fullname, Email, Subject and Message.

You will also notice 2 extra elements - a hidden field called 'action' which tells WordPress what to do with the form in its functions file. Plus a container with the success message which will appear once it has validated, therefore I have added some CSS which hides it by default.

Step 3:

Now lets process our custom contact form with some functions in the WordPress 'functions.php' file. This will use ajax via the admin-ajax.php.

This file should already exists and is called 'functions.php' and saved in your themes folder. What it contains are the functions which will process the form and send an email to the relevant email account. Also I have made a separate html email template which make them easier to design.

IMPORTANT: Note the usage of the 'yourwebsite_contactform' hidden 'action' value used in the form and where it is used in the functions below. These must match exactly.

<?php
// Function for handling the contact form
function yourwebsite_contactform_init() {
// This calls the javascript we just created for the form validation
wp_localize_script( 'ajax-contactus-script', 'wp_ajax', array(
'url' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( "ajax_nonce" ) // this is a unique token to prevent form hijacking
) );
// Enable any admin to run ajax_login() in AJAX and POST the form
add_action( 'wp_ajax_yourwebsite_contactform', 'yourwebsite_contactform_process' );
// Enable any user with no privileges to run ajax_login() in AJAX and POST the form
add_action( 'wp_ajax_nopriv_yourwebsite_contactform', 'yourwebsite_contactform_process' );
}
// Initiate the ajax enquiry form and add the validation javascript file
add_action( 'init', 'yourwebsite_contactform_init' );
add_action( 'wp_enqueue_scripts', 'yourwebsite_contactform_init' );
// Function to send the email using the email template
function yourwebsite_contactform_process() {
$to = array('your@emailaccount.com');
// If you want to send to several emails just add to the array like below
// $to = array( 'your@emailaccount.com', 'another@emailaccount.com' );
$subject = 'Email subject title';
// This is the way to transfer the form $_POST values to the email template
$postdata = http_build_query( $_POST );
$opts = array( 'http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$content = stream_context_create( $opts );
// Load the email template and create the email content
$message = file_get_contents( get_bloginfo( 'template_directory' ) . '/email-template/contact-form.php', false, $content );
// Set the email header which contains the forms fullname and the email address
$headers = 'From: ' . trim( $_POST[ 'fullname' ] ) . ' <' . trim( $_POST[ 'email' ] ) . '>' . "\r\n";
// Now loop through the $to email accounts
// If you don't do this it will send the email as a group send (i.e. each email account will see all the other email accounts)
foreach ( $to as $email_address ) {
wp_mail( $email_address, $subject, $message, $headers );
}
// return the value of 1 to show it has been successful
// The form needs to return this value to confirm the email has been sent
echo '1';
die();
}
// Set the default email type as html instead of text only
function yourwebsite_contactform_set_content_type(){
return "text/html";
}
add_filter( 'wp_mail_content_type','yourwebsite_contactform_set_content_type' );
?>

Step 4:

Create the email template to send your contact form details

And now the last part to create a html layout which will embed the contact form details and send it to your email account. We simply output the form values in a table form.

File called 'contact-form.php' and saved inside a folder called 'email-template' in your themes folder.

me@grafxflow

I am a Full-stack Developer who also started delving into the world of UX/UI Design a few years back. I blog and tweet to hopefully share a little bit of knowledge that can help others around the web. Thanks for stopping by!