0

After sending a contact form I got following error:

Warning: Cannot modify header information - headers already sent by (output started at /home/clientsc/public_html/mypage/wp-includes/general-template.php:2680) in /home/client/public_html/mypage/wp-includes/pluggable.php on line 1171

I got this error when I put the function below in the file named functions.php

function send_my_awesome_form(){

if (!isset($_POST['submit'])) {

    // get the info from the from the form
    $form = array();
    $form['fullname'] = $_POST['fullname'];
    $form['company'] = $_POST['company'];
    $form['email'] = $_POST['email'];
}

// Build the message
$message  = "Name :" . $form['fullname'] ."\n";
$message .= "Company :" . $form['company']  ."\n";
$message .= "Email :" . $form['email']     ."\n";

//set the form headers
$headers = 'From: Contact form <your@contactform.com>';

// The email subject
$subject = 'you got mail';

// Who are we going to send this form too
$send_to = 'myemail@gmail.com';

if (wp_mail( $send_to, $subject, $message, $headers ) ) {
    wp_redirect(home_url( )); exit;
}

 }

 add_action('wp_head', 'send_my_awesome_form');

How can I solve this issue?

Daniel
  • 79
  • 1
  • 7
  • Possible duplicate of [How to fix "Headers already sent" error in PHP](http://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php) – Qirel May 27 '16 at 14:40

1 Answers1

0

wp_head hook is used in the header of your theme, so it's too late and the HTML is already partially displayed.

You have to use the init hook instead :

add_action('init', 'send_my_awesome_form');

EDIT :

function send_my_awesome_form(){ 
    if( isset($_POST['fullname']) && isset($_POST['company']) && isset($_POST['email']) ){ 
        // your form treatment
        // your redirect
    } 
}
Pierre
  • 789
  • 1
  • 4
  • 15
  • Hi, I changed it according to your suggestion. Now I got another error: redirected you too many times. Webiste not working. – Daniel May 27 '16 at 14:24
  • It's becaure your code is played on every page load. You have to put all the code of your function in the `if` that checks the form ou want is posted – Pierre May 27 '16 at 14:34