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"]

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("".$_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 not show anywhere else in the form, or else it will get replaced!

Also, make sure to replace with your actual domain.

Related Posts

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

  1. Thank you so much. It solves exactly what I wanted.
    Share with me a Bitcoin Cash address so I can send you a tip

Leave a Reply

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

Captcha loading...