you can filter to ‘wpcf7_form_elements’ and replace something of defined (like a class) to add the attributes you need.
add_filter( 'wpcf7_form_elements', 'my_wpcf7_form_elements' );
function my_wpcf7_form_elements( $content ) {
// global $wpcf7_contact_form;
$content = str_replace( 'class=”wpcf7-form-control wpcf7-text', 'class=”wpcf7-form-control wpcf7-text” data-item=”item” aria-required=”true” aria-invalid=”false” ', content );
return $content;
}
Thread Starter
kkow
(@kkow)
Thanks @codekraft, but not really what I’m looking for here. Adding anything that way provides no control per input or per form even.
Thread Starter
kkow
(@kkow)
For anyone with this or a similar question, I put the following code snippet together. This allows you to add custom attributes that begin with ‘data-‘ to your tags for targeting or adding data later on. Similar to the way classes and ids work it cannot contain spaces or quotes. Hopefully this helps someone and it gets added as a much needed standard feature to the plugin.
function add_cf7_data_attributes( $content ) {
$contact_form = WPCF7_FormTagsManager::get_instance();
$tags = $contact_form->get_scanned_tags();
$data_tags = [];
// loop through tags and save any data attributes we find along with the corresponding tag name
foreach ( $tags as $tag ) {
foreach( $tag->options as $attr ) {
if ( strpos( $attr, 'data-' ) !== false ) {
$data_attr = explode( ':', $attr );
$data_tag = [
'name' => $tag->name,
'data_attr' => $data_attr[0] . '="' . $data_attr[1] . '"'
];
array_push( $data_tags, $data_tag );
}
}
}
// if we have any data attribute tags from above, search and replace them in the form
if ( !empty( $data_tags ) ) {
foreach ( $data_tags as $tag ) {
$search = 'name="' . $tag['name'] . '" ';
$replace = $search . $tag['data_attr'] . ' ';
$content = str_replace( $search, $replace, $content );
}
}
return $content;
}
add_filter( 'wpcf7_form_elements', 'add_cf7_data_attributes' );
-
This reply was modified 5 years ago by
kkow.
@kkow, very well done!
In fact it would be interesting to have a library of snippets for wpcf7, in addition to those documented there are a thousand other tricks!