0

I have this function that sends various emails for me:

function tps_send_email($emailTo, $subject, $content) {
    //Allow HTML in email
    function tps_set_html_email_content_type() {
        return 'text/html';
    }
    add_filter( 'wp_mail_content_type', 'tps_set_html_email_content_type' );

    //Send the email
    $mailSent = wp_mail($emailTo, $subject, $content);

    //Reset HTML content type back to text only (avoids conflicts)
    remove_filter( 'wp_mail_content_type', 'tps_set_html_email_content_type' );

    return $mailSent;
}

I use it so I don't have to set the content type manually each time I us wp_mail. But, if I use this function in another function more than once, like so:

function my_custom_function(){
    $mailTo = 'anemail@email.com';
    $subject = 'Some subject line';

    $emailTemplate1 = 'template 1 content goes here';
    tps_send_email($emailTo, $subject, $emailTemplate1 );

    if (some condition) {
        $emailTemplate2 = 'template 2 content goes here';
        //send another email
        tps_send_email($emailTo, $subject, $emailTemplate2  );
    }
}

The first email sends fine, but the 2nd email throws the error Fatal error: Cannot redeclare tps_set_html_email_content_type()... (which is a function within my tps_send_email() function).

What have I done wrong?

1

That's because you have put function tps_set_html_email_content_type inside the tps_send_email, and each time you call it, it will declare the tps_set_html_email_content_type function again. Just move it out:

function tps_set_html_email_content_type() {
    return 'text/html';
}

function tps_send_email($emailTo, $subject, $content) {
    add_filter( 'wp_mail_content_type', 'tps_set_html_email_content_type' );

    //Send the email
    $mailSent = wp_mail($emailTo, $subject, $content);

    //Reset HTML content type back to text only (avoids conflicts)
    remove_filter( 'wp_mail_content_type', 'tps_set_html_email_content_type' );

    return $mailSent;
}

I am not sure why you would put one function inside another one in the first place, but that is never a good idea, even so PHP supports it.

  • Ah, that makes sense and is a good rule of thumb. Thanks for the help! – Eckstein Sep 4 '17 at 17:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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