How to Pass Dynamic Data (Post ID / ACF Field) to Contact Form 7

Add dynamic data to a Contact Form 7 form

You or your client have a real estate website. It has many posts that describe properties, and each post has a Contact Form 7 form. The task is to add the property ID to the form, so you know which property the request came from. It does not matter how the ID is made, it can be the post ID or an ACF field. In our case it is an ACF field property_id.

Problem: How to add dynamic data (a property ID) to a Contact Form 7 form?

Solution: Traditionally, we will look at two ways: on the front end and on the back end.

Front-end way

First add a hidden field to the Contact Form 7 form:

[hidden property-id id:property-id]

Then fill it with jQuery. In my case the ID is shown on the property page, in the first element with the class .property-ref:

jQuery( function ( $ ) {
    if ( $( 'body.single-property' ).length ) {
        var propertyID = $( '.property-ref' ).first().text().replace( /[^0-9]/g, '' );
        $( '#property-id' ).val( propertyID );
    }
} );

Now [property-id] can be used in the mail template like any other field. A simpler option for the same is to print the ID in the template, for example in a data- attribute of the form container, and read it from there.

Back-end way

The visitor can change a hidden field, so it is more reliable to add the ID on the server, to the email the site owner receives. Add to functions.php:

<?php
// Add the property ID to the email
add_action( 'wpcf7_before_send_mail', 'add_property_id_to_mail', 10, 3 );

function add_property_id_to_mail( $contact_form, &$abort, $submission ) {
    // Only for our form with ID 16
    if ( 16 !== (int) $contact_form->id() ) {
        return;
    }

    // The post where the form was submitted
    $post_id     = (int) $submission->get_meta( 'container_post_id' );
    $property_id = get_field( 'property_id', $post_id );

    if ( $property_id ) {
        $mail = $contact_form->prop( 'mail' );
        $mail['body'] .= "\n\nProperty ID: " . sanitize_text_field( $property_id );
        $contact_form->set_properties( array( 'mail' => $mail ) );
    }
}

The form ID is in the form shortcode ([contact-form-7 id="16"]) and in the URL of its edit page.

NOTE: If the post ID itself is enough, no code is needed at all: Contact Form 7 has special mail tags. Put [_post_id], [_post_title] or [_post_url] into the mail template, and they are replaced with the data of the post where the form was submitted.

Sources:

  1. https://contactform7.com/special-mail-tags/