Hooking into the Jetpack contact form

The Jetpack form has various filters that allow for customization to different degrees. Here I’ll look at just one of them, grunion_contact_form_field_html. Since this filters the HTML of the contact form, one benefit is being able to add additional attributes to specific fields in the form.

Below are a couple of examples. These examples can be added to a site using a functionality plugin.

Restricting what URLs site visitors can enter into a Jetpack form URL field

In this example, we’re restricting URLs to only YouTube URLs. To do that, we’re making use of the ‘pattern’ attribute. The value of the attribute should be a regex, that is used to check against the specific input fields value. If the value added to the input field satisfies the regex, then the form submission will succeed (assuming there are no other further checks in place that may be stricter). In our example, since a YouTube URL would meet regular URL validation, then if the URL provided meets the pattern check it will continue to be validated properly on form submission.

The Jetpack form already uses a pattern attribute, so by using the grunion_contact_form_field_html filter we can replace it’s value. In addition, we can replace the value of setCustomValidity so that the message that displays under the URL field is more specific to what we want.

add_filter( 'grunion_contact_form_field_html', function( $rendered_field, $field_label, $id ) {
    if ( $field_label === 'Website' ) { // Update this value if your URL field has a different name.
        $rendered_field = preg_replace(
            '/pattern="([^"]*)"/',
            'pattern="^https:\/\/(?:(?:www\.)?youtube\.com|youtu\.be)\/.*$"',
            $rendered_field
        );
        // Update the custom validity message
        $rendered_field = preg_replace(
            '/setCustomValidity\\("[^&]*"\\)/',
            'setCustomValidity("Please enter a valid YouTube URL")',
            $rendered_field
        );
    }
    return $rendered_field;
}, 10, 3 )

For a little extra style, we can add some CSS too to make the URL field stand out more when it is highlighting that the URL is wrong.

add_action( 'wp_enqueue_scripts', function() {
   wp_register_style( 'my-custom-jetpack-form', false );
   wp_enqueue_style( 'my-custom-jetpack-form' );

   $custom_css = "
      .contact-form input[data-type-override=url][aria-invalid=true]:not(fieldset) {
         border-left: 4px solid var(--jetpack--contact-form--error-color);
      }
    ";

   wp_add_inline_style( 'my-custom-jetpack-form', $custom_css );
}

Add a max character limit to a text field

In another example, we can add a character limit to the message input field on a Jetpack contact form. The attribute ‘maxlength’ can be inserted into the HTML, and whatever value is set here will be the character limit in that field. Then, so as to prevent confusion if someone hits the limit, we can also add a span element underneath the message input field with an explanation of the max character length limit.

add_filter( 'grunion_contact_form_field_html', function( $rendered_field, $field_label, $id ) {
    if ( $field_label === 'Message' && strpos( $rendered_field, '<textarea' ) !== false ) {
        $rendered_field = preg_replace(
            '/<textarea/',
            '<textarea maxlength="500"',
            $rendered_field,
            1
        );

        $limit_text = sprintf(
            /* translators: %d: maximum number of characters allowed */
            esc_html__( 'Maximum %d characters allowed', 'your-text-domain' ),
            500
        );
        
        $rendered_field = str_replace(
            '</div>',
            '<span id="message-limit-' . esc_attr($id) . '" class="message-limit-text" style="display: block; margin-top: 4px; font-size: 0.8em; color: #666;">' . $limit_text . '</span></div>',
            $rendered_field
        );
    }
    return $rendered_field;
}, 10, 3 );

As you can see, the options are quite varied, just with this single filter. There are plenty of other form filters you can hook into as well.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Karen Attfield

Subscribe now to keep reading and get access to the full archive.

Continue reading