Getting default values from shortcode attributes

Getting default values from shortcode attributes

Sometimes you may feel that it would be useful if you could use values from [contact-form-7 ...] shortcode attributes.

In such cases, you can use the default:shortcode_attr form-tag option, which retrieves the field default value from shortcode attributes.

For example, let』s say you have a field named 「destination-email」 for the destination email address:

[email* destination-email]

To get the default value from shortcode attributes, add the default:shortcode_attr option to the form-tag:

[email* destination-email default:shortcode_attr]

Then, add an attribute with the same name as the field (「destination-email」 in this case) into the shortcode for the contact form:

[contact-form-7 id="123" title="Contact Form" destination-email="[email protected]"]

Is that all? Unfortunately, no; there is a necessary extra step.

Normally, a WordPress shortcode only takes predefined attributes, so you need to register the attribute beforehand.

Add the following code snippet to your theme』s functions.php file:

add_filter( 'shortcode_atts_wpcf7', 'custom_shortcode_atts_wpcf7_filter', 10, 3 );

function custom_shortcode_atts_wpcf7_filter( $out, $pairs, $atts ) {
$my_attr = 'destination-email';

if ( isset( $atts[$my_attr] ) ) {
$out[$my_attr] = $atts[$my_attr];
}

return $out;
}

That』s all! You』ll see 「[email protected]」 input in the field.
Share this:FacebookTwitterLike this:Like Loading...

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注