Change the form recipient in Contact Form 7 before sending mail

March 19, 2019

In some cases, I want to simplify the process for clients to change their contact form recipient address.  Rather than have them directly modify the Contact Form 7 settings, I would prefer if they changed the “To” setting when editing the contact page, or the site settings, or something else.  In my case, Advanced Custom Fields always provides a better editing experience to accomplish this.

To the short and sweet, add this to your theme’s functions.php  file:

Let’s talk about what’s happening here.

The wpcf7_before_send_mail is very powerful and allows you modify tons of things before the email sends.  You are creating a custom function here to change what those modifications are.  In this case, we are changing the recipient.

Now, I had mentioned before that I use Advanced Custom Fields to change how someone would update this, so let’s look at how to do that.

Let’s say that I have a contact page and that’s where I would like my client’s to edit the recipient address.  First, I would need to set up a Field Group for that page, and then create a field for them to enter that email address.  Let’s call it “Recipient” and the field name will be “recipient”.

The next part is determining how to grab that field value if we are outside of a loop. In ACF’s case, it’s very simple, but it is completely dependent on your site.  Simply put, you will need the POST ID of your page.  How do you find that?

Easily enough, you can find it in the URL when you are actually editing the page.  It would look just like this:

That “###” is your Post ID.  You can now call your “Recipient” field value outside of the loop:

Let’s put this all together in our function to make it dynamic:

Now, whenever someone edits the “Recipient” field in the Post you selected, the email address will get updated before the email sends out.  If it is left blank, CF7 will use the traditional “To” field to determine the recipient.

There is a ton more customization you can accomplish with this hook.  Don’t be afraid to explore more and have more control over the editing process you provide for your clients.  Thanks, and happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *