Contact Form 7 – Editing email output of tags

Have you ever needed to make small changes to the output that Contact Form 7 creates for emails? Change a certain word, replace certain characters, etc.? Well here’s the solution:

add_filter('wpcf7_mail_tag_replaced', tag_replace_function(), 10, 3);

Now, this is not a perfect solution, it’s fairly brutish in fact. CF7 did not see it fit to provide you with many avenues for editing the mail output. This filter only provides you with the following information:

  • The replaced text ($replaced)
  • The original values ($submitted)
  • Whether or not is it HTML ($html)

Using this information you can’t do a whole lot, unless you want some really broad changes.

 

The Scenario

In this case I had created a new CF7 shortcode that allows users to select their location in google maps. I then wanted to email a link to that location in the email that is generated by the submitted form. CF7 was making that a challenge because the array containing latitude and longitude was being output in the email as ‘50.0001, -4.003’ – the space completely ruining it for my google maps link.

The only solution to this, was to edit the output of my tag to remove the space. I could then generate a nice google maps link such as: https://www.google.co.uk/maps/place/50.0001,-4.003

Solution

Simply use the ‘add_filter’ code specified above, and then create a new function:

public function tag_replace_function ($replaced, $submitted, $html) {
 if (is_array($submitted) && array_key_exists('lat', $submitted) && array_key_exists('lng', $submitted)){
   $replaced = str_replace(array("%20", " "), "", $replaced);
 }
 return $replaced;
}

I could create a very specific replace in this situation because the data that was submitted was an array, and it had array keys ‘lat’ and ‘lng’. I then just replace the space character with nothing and I have the output required!

Published by

MHayward

I am a Web Developer who has been creating websites and hacking at WordPress for over 4 years. I'm a graduate of Surrey University where I studied Computer Science.

Find me on linked in http://uk.linkedin.com/in/mhayward89