WordPress – Contact form handler code in custom template fires from another custom template

First time posting a question here, so sorry for any mistakes I make!

I’m building a site in WordPress which has a contact form on the home page. In order to send an email off when someone fills it in, I created a custom page template, contact-success.php, created a page in the back end and applied the template:

Read More
<?php
/**
* Template Name: Contact Success
* Description: A Page Template shows contact success and sends email
*
* @package WordPress
* @subpackage Twenty_Eleven
* @since Twenty Eleven 1.0 
*/

get_header(); ?>

With a basic mail function to send the email:

<?php
$contact = $_POST['contact'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$query = $_POST['query'];

$message .= "The following form was submitted on the xxx websitennn";            $message .= 'Name: ' . $contact . "nn";
$message .= 'Phone: ' . $phone . "nn";
$message .= 'E-Mail: ' . $email . "nn";
$message .= 'Query: ' . $query . "nn";

if(mail('xxx@xxx.co.uk', 'New Contact Submission from ' . $contact, $message)) {
    echo('Successfully Sent');
} else {
    echo('Message Failed'); 
}

?>

Although the form submits correctly from my contact form and fires the email, it seems to also fire whenever I visit one of my other pages which has a different custom page template applied, location-results.php:

<?php
/**
* Template Name: Location Results
* Description: A Page Template that shows location results
*
* @package WordPress
* @subpackage Twenty_Eleven
* @since Twenty Eleven 1.0
*/

get_header(); ?>

Any ideas on what I’m doing wrong?

Many thanks, and if I need to give any further info just let me know!

Related posts

Leave a Reply