联系表单 7 自定义验证特定表单 ID

Gus*_*avo 0 php forms validation contact-form-7

我在联系表单 7 中使用自定义验证,但我需要验证特定表单,而不是所有表单。这是我的代码:

add_filter( 'wpcf7_validate_text*', 'my_custom_text_validation_filter', 20, 2 );
function my_custom_text_validation_filter( $result, $tag ) {

    $tag = new WPCF7_Shortcode( $tag );

    if ( 'name' == $tag->name ) { // validate name field only

        .... // my validation here

    }

    return $result;
}
Run Code Online (Sandbox Code Playgroud)

Gus*_*avo 5

CF7 总是向表单添加一个名为 的隐藏字段_wpcf7,其中包含表单 id。可以使用该字段在执行代码之前检查您正在验证的表单:

add_filter( 'wpcf7_validate_text*', 'my_custom_text_validation_filter', 20, 2 );
function my_custom_text_validation_filter( $result, $tag ) {

    if ( isset($_POST['_wpcf7']) && $_POST['_wpcf7'] != 166) // Only form id 166 will be validated.
        return $result;

    $tag = new WPCF7_Shortcode( $tag );

    if ( 'name' == $tag->name ) { // validate name field only

        .... // my validation here

    }

    return $result;
}
Run Code Online (Sandbox Code Playgroud)