0

i'm setting up a contact form in functions.php My problem is that when ever i refresh the page, the script sends a mail. This should only happen when someone submits the form. I would appreciate if someone could help

function myform(){    
        if($_SERVER['REQUEST_METHOD'] == 'POST') {    
            $navn = sanitize_text_field($_POST['navn']);

        if(!isset($error)){
            $to = 'test@email.com';
            $subject = 'test';    
            $body = '<h1>My text</h1>' . '<p>' . $navn . '</p>';        
            $headers = array('Content-Type: text/html; charset=UTF-8', 'Cc: test2@email.com');

            if(wp_mail( $to, $subject, $body, $headers )){
                wp_redirect( 'http://localhost:8888/test/takk/' ); exit;
            }    
        }
        }
        }

add_action('init', 'myform');
hb8
  • 83
  • 6
  • Posibly this will help https://stackoverflow.com/questions/8335828/how-to-delete-post-variable-upon-pressing-refresh-button-on-browser-with-php/8336492 – Cafer Yükseloğlu Jul 24 '19 at 22:15
  • 1
    Yes as you are using init hook for the above function the function is called everytime when a page is refreshed or when the header of the theme is running. So in this case you need to remove this hook you have used above so you will not face this issue. – Pratik bhatt Jul 25 '19 at 09:07
  • Thanks for the reply. Seems to be working if i change from init to get_header :) Would you say it's ok to use get_header instead? Or is it another hook i should use? – hb8 Jul 25 '19 at 10:25

0 Answers0