1

How do I call the WP_MAIL function from a page which has a form?

I would like to create a form in a page, and by pressing "Send" activate a function in the functions.php file, so the mail gets sent AND returning to a page where the form information is presented along with confirmation that the mail was actually sent.

Anybody

This is the form:

      <form action = "<?php $_PHP_SELF ?>" method = "GET">
         Name: <input type = "text" name = "name" />
         Age: <input type = "text" name = "age" />
         <input type = "submit" />
      </form>

Catching this in the content page does not work, should this be placed in the functions.php?

<?php
   if( $_GET["name"] || $_GET["age"] ) {
      echo "Welcome ". $_GET['name']. "<br />";
      echo "You are ". $_GET['age']. " years old.";

      exit();
   }
?>
1
  • Use a POST form, and hook into init, check if the form is submitted by checking isset( $_POST['SUBMIT_BTN_NAME_HERE'] ). Also use nonces as they are good for security.
    – Ismail
    Aug 23, 2016 at 16:40

1 Answer 1

1

This can (and should) be achieved using the admin_post action. Take a look at the docs for an example:

https://codex.wordpress.org/Plugin_API/Action_Reference/admin_post_(action)

SitePoint also have a more comprehensive tutorial here:

https://www.sitepoint.com/handling-post-requests-the-wordpress-way/

Hope that helps.

2
  • Will this also work when the visitors are not logged in as administrators?
    – AgoraLive
    Aug 23, 2016 at 10:09
  • @user2975926 Yes it will.
    – Matt Sims
    Nov 21, 2016 at 10:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.