Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a custom attribute?

How to add a custom attribute in the field Contact Form 7 without javascript ?

For example, there is such a field on the page:

<input type="text" name="name" class="form-control" id="name-1" data-attr="custom" data-msg="Текст 1"> 

Question: is it possible to set these custom attributes (data-attr, data-msg) of fields in the admin panel?

like image 261
HamSter Avatar asked Sep 18 '17 07:09

HamSter


People also ask

How do I create a custom attribute in HTML?

If you want to define your own custom attributes in HTML, you can implement them through data-* format. * can be replaced by any of your names to specify specific data to an element and target it in CSS, JavaScript, or jQuery.

What is a custom attribute?

Custom attributes. A custom attribute is a property that you can define to describe assets. Custom attributes extend the meaning of an asset beyond what you can define with the standard attributes. You can create a custom attribute and assign to it a value that is an integer, a range of integers, or a string.


2 Answers

Find the name of your field.

[text* text-21]

If the name of your field name="text-21", like in my example, add this code to functions.php file.

add_filter( 'wpcf7_form_elements', 'imp_wpcf7_form_elements' );
function imp_wpcf7_form_elements( $content ) {
    $str_pos = strpos( $content, 'name="text-21"' );
    if ( $str_pos !== false ) {
        $content = substr_replace( $content, ' data-attr="custom" data-msg="Foo Bar 1" ', $str_pos, 0 );
    }
    return $content;
}

Note, it will add those attributes to all forms elements where the name is text-21, if you want prevent it then give your form element some unique name [text* unique-name]

And change the code to

add_filter( 'wpcf7_form_elements', 'imp_wpcf7_form_elements' );
function imp_wpcf7_form_elements( $content ) {
    $str_pos = strpos( $content, 'name="unique-name"' );
    if ( $str_pos !== false ) {
        $content = substr_replace( $content, ' data-attr="custom" data-msg="Foo Bar 1" ', $str_pos, 0 );
    }
    return $content;
}
like image 82
Oleg Apanovich Avatar answered Oct 19 '22 03:10

Oleg Apanovich


Multiple attributes can be added also. eg

add_filter( 'wpcf7_form_elements', 'imp_wpcf7_form_elements' );

function imp_wpcf7_form_elements( $content ) {
    $str_pos = strpos( $content, 'name="your-email-homepage"' );
    $content = substr_replace( $content, ' aria-describedby="emailHelp" ', $str_pos, 0 );

    $str_pos2 = strpos( $content, 'name="your-fname-homepage"' );
    $content = substr_replace( $content, ' aria-describedby="fnameHelp" ', $str_pos2, 0 );

    $str_pos3 = strpos( $content, 'name="your-lname-homepage"' );
    $content = substr_replace( $content, ' aria-describedby="lnameHelp" ', $str_pos3, 0 );
    return $content;        
}
like image 23
Victor Drover Avatar answered Oct 19 '22 04:10

Victor Drover