Wordpress Contact form 7 custom shortcodes
There are two types of tags in CF7: form tags (the contact form itself) and mail tags (a email) — read more.
Custom form tags:
To add a custom form tag you can use
wpcf7_add_form_tag()
function onwpcf7_init
action hook (Read more).The
wpcf7_add_shortcode()
function in the accepted answer is considered to be deprecated and replaced by this function.Custom mail tags:
I didn't find any built-in functionality to add custom mail tags but I believe there are multiple possible workarounds here:
Enable custom shortcodes (don't forget to create the shortcode handler beforehand):
- For mail components, according to the DACrosby's answer.
- For entire mail (all components), using
wpcf7_special_mail_tags
filter:
function my_special_mail_tag( $output, $name, $html ) { if ( 'myshortcode' === $name ) { $output = do_shortcode( "[$name]" ); } return $output; } add_filter( 'wpcf7_special_mail_tags', 'my_special_mail_tag', 10, 3 );
- Add a custom hidden form tag with the prepopulated data to the form, and then use it in the mail:
[my-custom-form-tag-with-some-prepopulated-data]
; the custom form tag should be registered with thewpcf7_add_form_tag()
, as specified above.
This is a bit late to the response party, but I keep seeing this post when I want to add custom shortcodes to my forms and message body. I wanted to be able to insert shortcodes without registering them special in CF7 and often in the message body only (something CF7 doesn't seem to be able to do).
Here's how I finally did it:
// Allow custom shortcodes in CF7 HTML form
add_filter( 'wpcf7_form_elements', 'dacrosby_do_shortcodes_wpcf7_form' );
function dacrosby_do_shortcodes_wpcf7_form( $form ) {
$form = do_shortcode( $form );
return $form;
}
// Allow custom shortcodes in CF7 mailed message body
add_filter( 'wpcf7_mail_components', 'dacrosby_do_shortcodes_wpcf7_mail_body', 10, 2 );
function dacrosby_do_shortcodes_wpcf7_mail_body( $components, $number ) {
$components['body'] = do_shortcode( $components['body'] );
return $components;
};
// Add shortcode normally as per WordPress API
add_shortcode('my_code', 'my_code_callback');
function my_code_callback($atts){
extract(shortcode_atts(array(
'foo' => 'bar'
), $atts));
// do things
return $foo;
}
Add the following to your functions.php
wpcf7_add_shortcode('custom_date', 'wpcf7_custom_date_shortcode_handler', true);
function wpcf7_custom_date_shortcode_handler($tag) {
if (!is_array($tag)) return '';
$name = $tag['name'];
if (empty($name)) return '';
$next_week = date('Y-m-d', time() + (60*60*24*7));
$html = '<input type="hidden" name="' . $name . '" value="' . $next_week . '" />';
return $html;
}
Now in the "Form" field in CF7 GUI type [custom_date next_week]
Now you can use [next_week]
in the message body.