How to add a custom attribute?

前端 未结 4 2070
走了就别回头了
走了就别回头了 2021-02-04 07:53

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

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



        
4条回答
  •  深忆病人
    2021-02-04 08:38

    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;
    }
    

提交回复
热议问题