How to get URL of current page as hidden field in Contact Form 7 (CF7) plugin

While the dynamic text extension for Contact Form 7 is popular to use for grabbing the current page url that someone submits a form on, it’s not always suitable. For instance, if you are trying to integrate Contact Form 7 with Salesforce, the dynamic text extension may not work with the integration plugin.

There is also the option of using CF7’s special mail tags if you only need to populate these values in your email. But, the url shortcode here will not dynamically populate the current page url as a field value of the form.

So instead, let’s look at this simple solution that does not require any additional plugins. It’s purely PHP.

In your contact form, add your hidden field like this:

<div style="display:none;"> 
[text page-url "pageurl"]
</div>

Now to grab the current page URL and swap out the dummy “pageurl” value for the real URL, add this to your child theme’s functions.php:

add_filter( 'wpcf7_form_elements', function($form) { 
$val = esc_url("https://www.yourdomain.com".$_SERVER['REQUEST_URI']); 
$form = str_replace( 'pageurl', $val, $form ); 
return $form; 
} );

In this example, “pageurl” is the dummy value assigned to the text field. You can use anything you want here but make sure it’s a unique value that will show anywhere else in the form, or else it will get replaced!

Also, make sure to replace yourdomain.com with your actual domain.

Related Posts

Leave a Reply

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