A very basic question – how to properly use wp_mail() in a plugin

I have been trying for a while now to use wp_mail to send an email from within my plugin. The code I’m using is as follows.

function add_page_content_Send_Feed(){
    echo "<h2>Send your feed via email</h2>";


    echo "<form id='post' action='' method='POST'>";
    echo "<input type="submit" name="send_feed" value="Send my feed" id='submit';'/>";
    echo "</form>";

    // Example using the array form of $headers
    // assumes $to, $subject, $message have already been defined earlier...

    $headers[] = 'From: UltraIT <[email protected]>';
    $headers[] = 'Cc: John Q Codex <[email protected]>';
    $headers[] = 'Cc: [email protected]'; // note you can just use a simple email address

    $to = '[email protected]';
    $subject="TESTING";
    $message="hello"; 

    if(isset($_POST['send_feed'])) {
        wp_mail( $to, $subject, $message, $headers);
    }

} 

This however is not working… Can anyone tell me what I’m doing wrong?

1 Answer
1

Your code works well when put in a page template, so what is currently wrong in your case most probably is the usage of the wrong hook in the wrong place.

Just an example of how you can hook this:

add_action('ahook', 'add_page_content_Send_Feed'); //add this after your function definition

Then you can use this in any page or other template of the theme (or other plugin):

do_action('ahook');

‘ahook’ can be a hook you made up, but you can replace it by some specific one that you want to use depending on your specific case.

Another thing you can do is define a shortcode and apply this button just anywhere in your content.

Leave a Comment