How to add a custom attribute in the field Contact Form 7 without javascript ?
For example, there is such a field on the page:
Here is a generic solution that doesn't involve hardcoding the field name and the attributes
add_filter( 'wpcf7_form_tag', function ( $tag ) {
$datas = [];
foreach ( (array)$tag['options'] as $option ) {
if ( strpos( $option, 'data-' ) === 0 ) {
$option = explode( ':', $option, 2 );
$datas[$option[0]] = apply_filters('wpcf7_option_value', $option[1], $option[0]);
}
}
if ( ! empty( $datas ) ) {
$name = $tag['name'];
$tag['name'] = $id = uniqid('wpcf');
add_filter( 'wpcf7_form_elements', function ($content) use ($name, $id, $datas) {
return str_replace($id, $name, str_replace("name=\"$id\"", "name=\"$name\" ". wpcf7_format_atts($datas), $content));
});
}
return $tag;
} );
It works on all data attributes so you can use it like this
[text* my-name data-foo:bar data-biz:baz placeholder "Blabla"]
Output:
Since wpcf7 doesn't provide a way to hook into options directly the solutions uses a trick and temporary replaces the name of the field by a unique id that is then replaced in a later filter with the correct name and added attributes
If you need it to work with more than just data attributes you can whitelist some more attributes by replacing this line
if ( strpos( $option, 'data-' ) === 0 ) {
to something like the following
if ( preg_match( '/^(data-|pattern|my-custom-attribute)/', $option ) ) {