phpwordpresscontact-form-7

Contact Form 7 - Change email content after field replacement


I'm trying to make the text in the email that is sent to the admin all caps. I have gotten all caps to work, but the placeholders ([first-name], [last-name], [email], etc.) are not being replaced with the values. I don't know how to use the strtoupper() function on the email body AFTER the placeholders have been replaced.

This is my current code:

add_action("wpcf7_before_send_mail", "wpcf7_all_caps_email");

function wpcf7_all_caps_email($WPCF7_ContactForm)
{
    //Get current form
    $wpcf7 = WPCF7_ContactForm::get_current();
    // get current SUBMISSION instance
    $submission = WPCF7_Submission::get_instance();
    // Ok go forward
    if ($submission) {
        // get submission data
        $data = $submission->get_posted_data();
        // nothing's here... do nothing...
        if (empty($data)) {
            return;
        }

        $mail = $wpcf7->prop('mail');
        $mail['body'] = strtoupper($mail['body']);
        

        // Save the email body
        $wpcf7->set_properties(array(
            "mail" => $mail
        ));
        // return current cf7 instance
        return $wpcf7;
    }
}

This is what the mail that comes through looks like:

FROM:
[YOUR-NAME]

EMAIL:
[YOUR-EMAIL]

PHONE:
[YOUR-PHONE]

COMPANY: (EMPTY IF NOT ENTERED)
[COMPANY-NAME]

EVENT DATE:
[_FORMAT_EVENT-DATE "F JS Y"]

EVENT LOCATION INFORMATION:
[EVENT-ADDRESS]
[EVENT-CITY]

VENUE:
[VENUE-NAME]

NUMBER OF GUESTS:
[NUMBER-OF-GUESTS]

DELIVERY REQUESTED?
[DELIVERY]

MESSAGE:
[YOUR-MESSAGE]

REQUESTED ITEMS:

[YITH-REQUEST-A-QUOTE-LIST]

Solution

  • To convert all of the text from the email to uppercase, you have to do this after the string replacement is done. With that being the case, you'll have to use the filter wpcf7_mail_components this is applied after the string replacement, but before the email is actually sent.

    This filter passes the mail components in an array. Then you want to use DOMDocument to parse the HTML and make all of the text uppercase.

    With this being the case, you can use the format of your cf7 form tags in standard upper or lower case like [text your-field]

    add_filter( 'wpcf7_mail_components', 'dd_mail_componentns', 10, 1 );
    function dd_mail_componentns( $components ) {
        $dom = new DOMDocument();
        $dom->loadHTML( $components['body'] );
        $xPath = new DOMXPath( $dom );
        foreach ( $xPath->query( '/html/body//text()' ) as $text ) {
            $text->data = strtoupper( $text->data );
        }
        $components['body'] = $dom->saveXML( $dom->documentElement );
        return $components;
    }
    

    This has been tested and works for me.