How to get current url in contact form 7

I’m using Contact Form 7 in my wordpress installation. I need to somehow pass a hidden field with the current page url in the contact form hidden field. I tried their custom function and tried the short code, no luck.

wpcf7_add_shortcode('sourceurl', 'wpcf7_sourceurl_shortcode_handler', true);

function wpcf7_sourceurl_shortcode_handler($tag) {
    if (!is_array($tag)) return '';

    $name = $tag['name'];
    if (empty($name)) return '';

    $html="<input type="hidden" name="" . $name . '" value="http://' . $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"] . '" />';
    return $html;
}

In the form edition I tried [sourceurl thesource]

4 s
4

See this example on how to create and parse the shortcode in the contact form 7 to use it add [current_url]

add_action( 'wpcf7_init', 'wpcf7_add_form_tag_current_url' );
function wpcf7_add_form_tag_current_url() {
    // Add shortcode for the form [current_url]
    wpcf7_add_form_tag( 'current_url',
        'wpcf7_current_url_form_tag_handler',
        array(
            'name-attr' => true
        )
    );
}

// Parse the shortcode in the frontend
function wpcf7_current_url_form_tag_handler( $tag ) {
    global $wp;
    $url = home_url( $wp->request );
    return '<input type="hidden" name="'.$tag['name'].'" value="'.$url.'" />';
}

Also if its all about to get the URL in the email you dont need all of this. there is a special tag for the email [_url] CF7 Special mail tags

Leave a Comment