Friday, November 25, 2011

[WordPress Contact Form 7] Add Numeric Type Field

This is about adding a numeric type "num" in Contact Form 7 (CF7, version 3.0.1) with minimum effort. This type only allows input to be numbers. Basically we will reuse a lot of the existing code in \wp-content\plugins\contact-form-7\modules\text.php It doesn't matter where do you put the code as long as they are in the same file.

1.
Register two shortcode:
wpcf7_add_shortcode( 'num', 'wpcf7_text_shortcode_handler', true );
wpcf7_add_shortcode( 'num*', 'wpcf7_text_shortcode_handler', true );

2.
Register the validation filter and implement the filter:
add_filter( 'wpcf7_validate_num', 'wpcf7_num_validation_filter', 10, 2 );
add_filter( 'wpcf7_validate_num*', 'wpcf7_num_validation_filter', 10, 2 );

function wpcf7_num_validation_filter( $result, $tag ) {
    $type = $tag['type'];
    $name = $tag['name'];

    $_POST[$name] = trim( strtr( (string) $_POST[$name], "\n", " " ) );

    if ( 'num' == $type || 'num*' == $type ) {
        if ( 'num*' == $type && '' == $_POST[$name] ) {
            $result['valid'] = false;
            $result['reason'][$name] = wpcf7_get_message( 'invalid_required' );
        } elseif ( '' != $_POST[$name] && ! is_numeric( $_POST[$name] ) ) {
            $result['valid'] = false;
            $result['reason'][$name] = 'Numbers are required.';
        }
    }

    return $result;
}


3.
You can try to add your Tag Generator for the new type, but I just don't bother. To use the new field, it is the same as using [text] field, e.g. [num mobile /10 class:mobile]

3 comments:

  1. Nice solution, however I am receiving an error on submission. It reads:

    Failed to send your message. Please try later or contact the administrator by another method.

    Any ideas on a fix?

    TIA
    ~Rat

    ReplyDelete
  2. sorry for digging out such an old post but I just wanted to confirm that this hack works
    we've just introduced it into client's website

    Contact form 7 Version 3.2.1
    Wordpress version 3.4.1

    ReplyDelete
  3. Hello! I just wish to give an enormous thumbs up for the nice info you've got right here on this post. I will probably be coming back to your weblog for more soon! wordpress autoblog setup

    ReplyDelete