Customizing mail-tag replacement

A mail-tag has a corresponding form-tag; when an email is composed, a mail-tag in the email template is replaced with the user input value that comes through the input field represented by the corresponding form-tag.

By default a mail-tag is replaced with the raw value the submitter inputs. You are able to customize this mail-tag replacement. To do this you use the wpcf7_mail_tag_replaced filter hook, as shown in the following example:

add_filter( 'wpcf7_mail_tag_replaced',

  function( $replaced, $submitted, $html, $mail_tag ) {
    if ( is_numeric( $submitted ) ) {
      $replaced = number_format( $submitted );
    }

    return $replaced;
  },

  10, 4
);

This filter function (notice that examples in this post use anonymous functions that are available in PHP 5.3 and higher) formats numerical values using the number_format function. When “1234567890” is the user input you will see “1,234,567,890” in the email message.

The wpcf7_mail_tag_replaced filter hook passes four parameters to a hooked function: $replaced, $submitted, $html, and $mail_tag.

$replaced has the value generated as the result of mail-tag replacement.

$submitted has the original value that has been input by the submitter.

$html has a boolean value; true if the mail-tag is used in an HTML message body.

$mail_tag has a WPCF7_MailTag object that represents the mail-tag itself.

Targeting a specific field

In the above example code the number_format function was applied to every field where the input was a numerical value. If you want to target a specific field you can do so by using the fourth $mail_tag argument, like in this example:

add_filter( 'wpcf7_mail_tag_replaced',

  function( $replaced, $submitted, $html, $mail_tag ) {
    if ( 'your-number' == $mail_tag->field_name() ) {
      if ( is_numeric( $submitted ) ) {
        $replaced = number_format( $submitted );
      }
    }

    return $replaced;
  },

  10, 4
);

By doing it this way the number_format is applied only when the field name of the mail-tag is ‘your-number’.

Targeting a specific form-tag type

There are variants of the wpcf7_mail_tag_replaced filter hook that are applied only to mail-tags corresponding to form-tags of a specific form-tag type. These filter hooks have the form-tag type as a suffix.

For example, use the wpcf7_mail_tag_replaced_number hook when you want to target form-tags of the number type:

add_filter( 'wpcf7_mail_tag_replaced_number',

  function( $replaced, $submitted, $html, $mail_tag ) {
    if ( is_numeric( $submitted ) ) {
      $replaced = number_format( $submitted );
    }

    return $replaced;
  },

  10, 4
);