Ready contact forms for contact form 7. Tips, hacks, secrets. Static or floating message

It took to get beautiful shape for a plugin, a form is needed yesterday, but it is quite difficult to sit and write styles by hand, and for many projects it simply does not work on budget. Therefore, I went in search of interesting plugins for quick setup css of contact forms.

All together (this applies to search engines) recommended - wise people said - correct css and do not fool anyone's head, "Notepad" in hand and go. Looking ahead, the wise people were right.

However, curiosity prevailed and it was decided to test the plugin in more detail, I had already tried it before, but it seemed extremely dull and inconvenient. The plugin hasn't been updated in 11 months, which is sad. A little more than 6K webmasters risked trusting their forms to him, also not a large number (of which I rocked it four or five times).

After installation, it creates a "Contact style" section in the root of the admin menu. In this section there are two items containing templates for Valentine's and Christmas and "Custom Style" where you can completely customize the form output. Actually the section "Custom Style" interests most of all, in more detail about the available settings:

"GENERALS SETTINGS" - you can define the background color, shape width (set in px,% did not try), border thickness, shape (dotted line, solid, etc.), color, rounding.

"INPUTS AND LABELS SETTINGS" - the background of the input fields, the color of the input font, the font (the list is not large and there will hardly be anything with the Cyrillic alphabet) and its size. Border color of fields, style (solid dotted line, etc.), thickness, rounding. Input font and its size. Margin parameters in px - height / width, padding. Font label, style, size, color.

"SUBMIT BUTTON SETTINGS" - settings of the button for submitting the form. Available settings are button size, rounding, color, border type and color.

Problems in use.

After reviewing the settings, you can come to the conclusion that everything is very good - practice has shown the opposite. There are really many settings, but they are not enough - there are no indentation settings inside the form, so all blocks are collected on the left border close to the edge of the form. Strange default settings - where the input field is 100 * 100 px. If you set the correct size of the fields, then the drop-down list will not be affected and it will drag the style of the main theme. It was not possible to reset to the original settings until the plugin was uninstalled ...

So far, except for manually changing the styles, it has not turned out more or less decently ... The miracle did not happen.

Important note! The plugin has recently been updated and something has changed in the settings quite significantly, so you need to watch and test.

DOM events

By monitoring DOM events, you can do anything at the right time while working with the form. For example, after successfully submitting a form, say "Thank you" in a pop-up window or redirect the user to another page.

List of form events

Wpcf7invalid Fires when the form has been successfully submitted to the server, but mail was not sent because there were fields with invalid input. wpcf7spam Fires when a form has been successfully submitted to the server, but mail was not sent because possible spam activity has been detected. wpcf7mailsent Fires when the form has been successfully submitted to the server and mail sent to the addressee. wpcf7mailfailed Fires when a form has been successfully submitted to the server, but failed to send mail... This may be due to the fact that the mail server does not work on the hosting. wpcf7submit Fires when the form has been successfully submitted to the server, regardless of other incidents. We pressed the "Submit" button - this action worked. wpcf7beforesubmit Triggered before the wpcf7submit event, which allows you to perform any manipulations with formData - form data that will be sent to the server. The event was added in CF7 v4.9.

The code from the examples below should be used wherever the form is displayed. If your form is displayed on all pages of the site, then a good solution would be to place the code in the footer.php file, since this template is used on all pages of the site.

Examples for the wpcf7submit event

The code below is a simple example of registering an event handler. In this example, the function listens for the wpcf7submit event from the container with the wpcf7 class and simply issues a warning when it occurs, that is, when you click the "Send" button, it immediately calls the message "Opachki, they are trying to send me ... to Magadan!". Note that the element with the wpcf7 class is a DIV with a form inside, the plugin generates all this on its own. If you have multiple forms on the page, the code will work only for the first found form... Of course, you replace the unnecessary alert () with a more useful action, for example, a nice animation for submitting a form.

// We are looking for a block with a form that has the wpcf7 class (all divs with a form have it) var wpcf7Elm = document.querySelector (". Wpcf7"); // Monitor the wpcf7submit event for the selected block wpcf7Elm.addEventListener ("wpcf7submit", function (event) (alert ("Opachki, they are trying to send me ... to Magadan!"); // Or something more useful), false) ;

If you want to monitor some specific form (below in the article there will be alternative solutions, more rational), then indicate the container ID:

// Looking for a unique block with a form by its ID var wpcf7Elm = document.querySelector ("# wpcf7-f92-p95-o1"); // Monitor the wpcf7submit event here, as in the previous example.

The examples above are designed to work with one form. If there are several forms on the page and you need to monitor the wpcf7submit event (or others) for everyone, then we hang the event not on a separate block, but on the entire document:

Document.addEventListener ("wpcf7submit", function (event) (alert ("Someone submitted a form! Which one? I don't know yet.");), False);

How to track entered data into fields

The custom data is passed to the event handler as the detail.inputs property of the event object. The detail.inputs data structure is an array of objects, and each object has name and value properties. Let's say the form has 4 fields. We use the code:

Document.addEventListener ("wpcf7submit", function (event) (var inputs = event.detail.inputs; console.log (inputs);), false);

When you click the "Submit" button, the data structure will be displayed in the browser console:

The name of each form field is available to us (the field name is indicated in the admin panel in the field tag and is required attribute) and its meaning.

You can iterate over each field and react to a certain one like this:

Document.addEventListener ("wpcf7submit", function (event) (var inputs = event.detail.inputs; // Look for a field named your-name and abuse the alert "when finding the for field (var i = 0; i< inputs.length; i++) { if ("your-name" == inputs[i].name) { alert(inputs[i].value); break; } } }, false);

There are other properties of the event object that you can use in your handler.

Detail.contactFormId The ID of the contact form. This ID can be seen in the admin panel in address bar when editing a form or in the form's shortcode itself. detail.pluginVersion Version of the Contact Form plugin 7. detail.contactFormLocale Language code of the form. For example, ru_RU. detail.unitTag Contact form unit tag. Each form has its own, for example wpcf7-f92-p95-o1. detail.containerPostId ID of the post containing the form.

You can view all the data like this:

Document.addEventListener ("wpcf7submit", function (event) (console.log (event.detail);), false);

How to handle a specific shape

For example, if you only want to do something with a specific contact form (ID = 123), use the detail.contactFormId property as shown below:

Document.addEventListener ("wpcf7submit", function (event) (if ("123" == event.detail.contactFormId) (alert ("Contact form with ID = 123."); // Do something else)), false);

Fighting spam with Akismet

How to deal with spam in the Contact Form 7 plugin? Several mechanisms are provided, but only a couple are popular: reCAPTCHA and Akismet.

How do I install and configure Akismet? At WordPress installation Akismet plugin is installed automatically, it remains only to activate it. If for some reason it is not there, then these links will help you:

After activating the plugin, a message will appear prompting you to activate your account:

When you click on the button, you will be taken to the plugin settings page:

For Akismet to work, you need to specify the API key in the plugin settings. If it is not there, then click the "Get API Key" button and follow the instructions:

  • Registration for off. plugin site using wordpress.com account
  • Choice tariff plan(there is a free one)
  • Adding a site to the admin panel of the service by clicking the "Activate this site" button

This is a simple and quick process. After activating the site, a redirect will occur back to the admin panel of your site with ready-made settings, they need to be saved:

In order for Akismet to start checking the field, you need to specify when it is generated by what rule to check, for example:

Akismet: author Add this parameter to the username input field.
Example: akismet: author_email Add this parameter to the user email field.
Example: akismet: author_url Add this parameter to the field for entering a link from the user.
Example:

It is recommended to use the akismet: value parameter for all fields that allow for this check. Based on the collected data, Akismet will decide whether it is spam or not, so completeness is essential.

Contact Form 7 has several types of notification design:

Green frame at the notification Message sent successfully Yellow frame at the notification Some fields are filled with an error, the field has not been validated Orange frame at the notification Message is marked as spam Red border at the notification Message sending failed

Now you can test the work of the form with Akismet protection by typing "viagra-test-123" instead of the username. A message with such data will be marked as spam and will not be sent by email.

Restricting access to the administration panel

Initially, the Contact Form 7 tab is available to all users with the contributor role and above. Only editors and administrators can edit forms. How do I change access rights to forms?

Access parameters are changed using constants that are written in the engine root in the wp-config.php file, for example:

Define ("WPCF7_ADMIN_READ_CAPABILITY", "manage_options"); define ("WPCF7_ADMIN_READ_WRITE_CAPABILITY", "manage_options");

By default, site admins and super admins have the manage_options right. That's why given example will give access to the list of forms and the ability to edit them only to users with these roles. Other roles will not see the plugin tab.

WPCF7_ADMIN_READ_CAPABILITY Minimum role or ability to access the admin panel, that is, display the menu and list of forms.
Default: edit_posts WPCF7_ADMIN_READ_WRITE_CAPABILITY Minimum Role or Capability for Form Editing. This parameter must be stricter or the same as WPCF7_ADMIN_READ_CAPABILITY. This is explained by the fact that you cannot edit forms without having access to the admin panel.
Default: publish_pages

For a better understanding of how this works, take a look at the code (CF7 v4.9.1, capabilities.php file) using these constants:

Add_filter ("map_meta_cap", "wpcf7_map_meta_cap", 10, 4); function wpcf7_map_meta_cap ($ caps, $ cap, $ user_id, $ args) ($ meta_caps = array ( "wpcf7_edit_contact_form" => WPCF7_ADMIN_READ_WRITE_CAPABILITY, "wpcf7_edit_contact_forms" => WPCF7_ADMIN_READ_WRITE_CAPABILITY, "wpcf7_read_contact_forms" => WPCF7_ADMIN_READ_CAPABILITY, "wpcf7_delete_contact_form" => WPCF7_ADMIN_READ_WRITE_CAPABILITY, " wpcf7_manage_integration "=>" manage_options "," wpcf7_submit "=>" read ",); $ meta_caps = apply_filters (" wpcf7_map_meta_cap ", $ meta_caps); $ caps = array_diff ($ caps); array_keys ($ meta_caps [$ cap])) ($ caps = $ meta_caps [$ cap];) return $ caps;)

From the code, you can see that the array of possibilities passes through the wpcf7_map_meta_cap filter, and contains the following data:

By default Array (=> publish_pages => publish_pages => edit_posts => publish_pages => manage_options => read) After changing, for example, using constants Array (=> manage_options => manage_options => manage_options => manage_options => manage_options = > read)

Thanks to the wpcf7_map_meta_cap filter, we can change this array. This way saves us from editing the wp-config.php file, but we have to write code, for example, in the functions.php file:

Add_filter ("wpcf7_map_meta_cap", "change_wpcf7_map_meta_cap"); function change_wpcf7_map_meta_cap ($ meta_caps) (// New feature value $ replace_caps = array ("wpcf7_edit_contact_form" => "manage_options", "wpcf7_edit_contact_forms" => "manage_options", "wpcf7_formopcontact7> manage_options ",); return array_replace ($ meta_caps, $ replace_caps);)

Design of checkboxes and radio buttons

Contact Form 7 lines up checkboxes and radio buttons by default. But this can be changed with the tag settings of these fields and simple CSS rules.

This is what the default checkboxes look like:

But if you pass the label_first parameter to the checkbox tag, the display of the label relative to the checkbox will change to the opposite:

To stack the checkboxes in a column, add a line of styles to the theme's CSS file:

Span.wpcf7-list-item (display: block;)

To line up the checkboxes as a table, add a line of styles to the theme's CSS file (optionally using the label_first parameter):

Span.wpcf7-list-item (display: table-row;) span.wpcf7-list-item * (display: table-cell;)

Loading JavaScript and CSS as needed

By default, Contact Form 7 loads JavaScript and CSS on all pages of the site, regardless of where the form is used. Technically, the plugin cannot work otherwise, but it can be "prompted".

Example 1 - completely disable JavaScript and CSS and enable where needed

Step 1 - disable JavaScript and CSS on all pages of the site

There is a WPCF7_LOAD_JS constant with a default value of true, which is defined in the plugin code and is responsible for loading JavaScript on all pages of the site. It can be overridden by inserting the following code into the wp-config.php file:

Define ("WPCF7_LOAD_JS", false);

This code will cancel the loading of plugin scripts.

And the same constant is for WPCF7_LOAD_CSS styles, which works on the same principle - it cancels loading of plugin styles:

Define ("WPCF7_LOAD_CSS", false);

From plugin version 3.9 and above, you can disable loading JavaScript and CSS via hooks in functions.php:

Add_filter ("wpcf7_load_js", "__return_false"); add_filter ("wpcf7_load_css", "__return_false");

But now we have another problem - on the page with the form, the styles and scripts of the plugin are not loaded, but the functionality and appearance spoiled. We need a mechanism that would solve the problem.

Step 2 - uploading files on form pages

For example, we have a Contact page with a form. The contact.php file is responsible for displaying the page. Then, let's use the code:

If (function_exists ("wpcf7_enqueue_scripts")) (wpcf7_enqueue_scripts ();) if (function_exists ("wpcf7_enqueue_styles")) (wpcf7_enqueue_styles ();)

This construct must be placed in the contact.php file before calling the wp_head () function. This is a recommendation from the plugin developer.

Example 2 - disabling scripts and styles wherever NOT needed

There is a more flexible method that allows you to specify on which pages to include scripts. This code need to be inserted into functions.php:

Option 1:
## Disable styles, plugin scripts everywhere except for the contacts page add_filter ("wp", "cf7_disable_css_js"); function cf7_disable_css_js () (if (! is_page ("contacts")) (add_filter ("wpcf7_load_js", "__return_false"); add_filter ("wpcf7_load_css", "__return_false");))
Option 2:
## Disable styles, plugin scripts everywhere except for the contacts page add_action ("wp_print_styles", "my_deregister_javascript", 100); function my_deregister_javascript () (if (! is_page ("contacts")) (wp_deregister_script ("contact-form-7"); // disable plugin scripts wp_deregister_style ("contact-form-7"); // disable plugin styles))

Example 3 - including scripts only when using the form shortcode

First, we unplug the JS and CSS, and then plug it back in only when the form's shortcode is triggered. Thus, the files will be included only on those pages where there is a form shortcode.

Function wpcf7_remove_assets () (add_filter ("wpcf7_load_js", "__return_false"); add_filter ("wpcf7_load_css", "__return_false");) add_action ("wpcf7_inf_c." function wpcf7_add_assets ($ atts) (wpcf7_enqueue_styles (); return $ atts;) add_filter ("shortcode_atts_wpcf7", "wpcf7_add_assets");

The code can be styled as a plugin or inserted into the theme's functions.php.

Tracking Forms with Google Analytics

There is an easy way to track the events of the form via Google analytics.

First, make sure you have the Google Analytic code, which looks something like this:

If you have the Analytics code or after installing it, you can send data to the system, which can then be monitored in the Google Analytics admin panel. Read more about this in the official documentation on event tracking.
For example, you need to track the submission of a form, for this you need to execute the following code:

Ga ("send", "event", "Contact Form", "submit");

The final step is to insert this JavaScript snippet into the HTML header ( ) of each page. You can edit your theme's header.php template for this, or you can use the wp_head functions.php hook on the hook.

And this is how you can track the successful submission of each individual form:

Document.addEventListener ("wpcf7mailsent", function (event) (if ("123" == event.detail.contactFormId) (ga ("send", "event", "Contact Form 123", "submit");) if ("253" == event.detail.contactFormId) (ga ("send", "event", "Contact Form 253", "submit");)), false);

Now, upon successful submission of the form, you will see this event in the Google Analytics admin panel (Behavior -> Events -> Overview). Perhaps the data will not appear there immediately after the event, but after 24-48 hours.

Selecting a recipient in the form

Let's imagine that you have a small web studio with staff: SEO, salesperson and technical support. How to send information to one of them personally using one form? The select field (drop-down list) will come to the rescue! The problem is solved in two stages.

Stage 1 - adding a tag to the form template:

Stage 2 stage - inserting a tag into the "To" field, which, when sending a letter, will take the mail selected by the user from our drop-down list and substitute it into the field.

This method has a serious drawback. Take a look at the code after transforming our dropdown tag:

As you can see, the addresses Email"stored" in an open form. The ubiquitous spammers can take advantage of this. But not after a little trick ... Let's update our tag like this:

Here we passed the parameter through the so-called pipe (forward slash) according to the rule name | value. As a result, we got the following html structure at the exit:

As you can see, in the form, the user selects one of the items, and the plug-in when sending the letter itself takes the value based on the name of the selected item.

Let's complicate the task even more ...

Imagine a situation when you need to send a letter to a selected addressee, for example, SEO, and another copy of the letter to the site manager for control.

In previous articles, we considered that Contact Form 7 can send two letters, and for each recipient, you can set a separate template.

So, the first copy comes to SEO and he understands what the message is about. But the manager does not understand which specialist the letter was addressed to, because he may not fully understand the topic or not remember all the mailing addresses of the specialists. There is a need for a letter template to use not only the value of the field (in our case, the email address), but also the heading of the item (name of the specialist)? To do this, the plugin provides us with the [_raw_ (field name)] tag, where (field name) is the name of our field. To summarize the use of tags:

The value of the field, which in the email template is converted to the value of the selected item (the email address in our example, that is [email protected]) [_raw_your-recipient] the name of the field, which in the letter template is converted to the name (title) of the selected item (the name of the specialist in our example, that is, Seoshnik)

If this functionality is not needed, then it can be disabled by entering the following code into the wp-config.php file:

Define ("WPCF7_USE_PIPE", false);

Adding Cc, Bcc and other email headers

Contact Form 7 in the tab with setting the email template has a field for sending additional headers (Additional Headers) according to the rule name-header: value. Each heading should start on a new line.

Consider the most popular ones - Reply-To, Cc and Bcc, read about the rest on Wikipedia.

Reply-To The name and address where replies to this letter should be addressed. For example, you asked the user to enter their email address in the form. Use it to mail client immediately knew which email to send the answer to. Cc (from the English carbon copy) contains the names and addresses of the secondary recipients of the letter to which the copy is sent. Bcc (from English blind carbon copy) contains the names and addresses of the recipients of the letter, whose addresses should not be shown to other recipients.

Contact Form 7 in your language

Contact Form 7 automatically uses the translation of the language that you use in the admin area. The language is changed in Settings -> General -> Site language (drop-down list). But this will change the language for the entire site. But what to do when your authors speak different languages?

To do this, the developers suggest using the Bogo plugin, which for each user makes it possible to switch the admin panel language. After activation, a language switch will appear in the toolbox next to your nickname.

Special email tags

Contact Form 7 supports a few specific tags that you might need when working with a form. For example, in the letter indicate the IP of the sender and the link of the page where the form was filled out. Special tags can be used in email templates or other form fields.

Submit tags

[_remote_ip] This tag will be replaced with the user's IP. [_user_agent] This tag will be replaced with the User Agent of the user's browser. User Agent is a string that web browsers use as their name, it contains not only the name of the browser, but also the version operating system and other parameters. [_url] This tag will be replaced with the URL of the page from which the form was submitted. [_date] Will be replaced by the date the form was submitted. [_time] Will be replaced at the time the form is submitted. [_invalid_fields] This tag is replaced by the number of form fields with invalid input. Use in notification templates. [_serial_number] Will be replaced with the sequence number of the stored message. The Flamingo 1.5+ plugin must be installed, described below.

Post tags

These tags will only work in the post content. If the form in a modal window, sidebar, footer or header is embedded in the theme template, that is, outside the post content, they will not work.

[_post_id] Will be replaced with the post ID in the content of which the form is displayed. [_post_name] Will be replaced with the name (slug) of the post from which the form was submitted. [_post_title] Will be replaced with the title (title) of the post from which the form was submitted. [_post_url] Will be replaced with the link (url) of the post from which the form was submitted. [_post_author] Will be replaced with the name of the author of the post from which the form was submitted. [_post_author_email] Will be replaced with the email of the author of the post from which the form was submitted.

Site tags

[_site_title] Will be replaced by the site name (specified in General Settings). [_site_description] Will be replaced by the site description (specified in General Settings). [_site_url] Will be replaced with the site address (specified in General Settings). [_site_admin_email] Will be replaced with the site's e-mail address (specified in General settings).

User tags

These tags provide information about the current registered user.

[_User_ *] tags only work when Sender It has account and logged in. If the form is submitted by an unauthorized user, then these tags will return an empty result and there will be no sense from them. It is recommended to enable the "" mode so that the form is displayed only for registered users.

If you want to use these tags and do not need to use the subscribers_only: true option, you need to enable the nonce option. If all this is not done, the data of authorized users will be reset via WP REST API and the specified tag will be skipped (replaced with an empty string).

[_user_login] Will be replaced with the username. [_user_email] Will be replaced with the user's email. [_user_url] Will be replaced with the URL of the user's site. [_user_first_name] Will be replaced with the username. [_user_last_name] Will be replaced with the user's last name. [_user_nickname] Will be replaced with the user's nickname. [_user_display_name] Will be replaced with the user's display name.

Saving sent messages with Flamingo

// You can do the same using the filter add_action ("wpcf7_autop_or_not", "__return_false"); WPCF7_USE_PIPE When the constant value is false (default is true), Contact Form 7 starts to accept | as a normal character. WPCF7_ADMIN_READ_CAPABILITY Minimum role or ability to access the admin panel.
Default: edit_posts... WPCF7_ADMIN_READ_WRITE_CAPABILITY Minimum Role or Capability for Form Editing. By default publish_pages. This parameter must be stricter or the same as WPCF7_ADMIN_READ_CAPABILITY. This is because you cannot edit forms without access to the administration panel. WPCF7_CAPTCHA_TMP_DIR Defining this constant will override the folder path for temporary CAPTCHA files. WPCF7_CAPTCHA_TMP_URL Defining this constant will override the folder reference for temporary CAPTCHA files. WPCF7_UPLOADS_TMP_DIR Defining this constant will override the temporary folder path for downloaded files. WPCF7_VERIFY_NONCE

Tells the plugin to check nonce ( security code) or not. Since plugin version 4.9, this constant has become false, that is, "do not check". You can return the check by setting the constant value to true or using a hook

Add_filter ("wpcf7_verify_nonce", "__return_true");

Redirecting to another address after submitting the form

When you need to redirect the user to a page after a successful form submission, for example, with a thank you or a gift, use the JavaScript hook:

See DOM Events for an explanation of how this works.

WordPress spam blacklist for filtering forms

If you are suffering from an influx of spam or unwanted messages, and CAPTCHA or Akismet fail, the "Black List" functionality built into the engine can help out.

The blacklist is located in the admin panel along the Settings -> Discussion path.

If a message sent via Contact Form 7 contains any of these words in its text, author name, URL, e-mail address or IP address, it will be marked as spam and will not be sent. Each word or IP on a new line. Search by substring is used, that is, by the word "buy" will be found "buy".

How do I find out the IP address from which spam comes through the Contact Form 7? The easiest way is to use the special tag [_remote_ip]. This tag is inserted into the email template and will be replaced with the sender's IP address when the email is sent.

Contact Form 7 form design

I often cite the html code of one or another field in Contact Form 7. You can see which classes the plugin adds to the fields by default. And now we will briefly go over how to set custom classes for form fields.

What CSS to edit to change the appearance of the form?

All styles that are responsible for the external form feed are stored in the plugin file contact-form-7 / includes / css / styles.css. It is not a good idea to change this file, as updating the plugin will replace the file and you will lose all changes. The same goes for public themes, which are also updated like plugins.

Therefore, to change styles, you need to select a style file that will not update. This can be a child theme stylesheet. Alternatively, you can use the theme settings, which allow you to insert CSS code into a special field.

If you have your own theme, you can change (interrupt) the Contact Form 7 styles in the theme styles.

Field Styles in Contact Form 7

The plugin supports many types of fields, but the most common type of field is text. To set a style for such a field, you need to refer to it by type:

Wpcf7 input (background-color: #fff; color: # 000; width: 50%;)

We often use more than one field in the form, so let's add properties to several at once:

Wpcf7 input, .wpcf7 input, .wpcf7 textarea (background-color: #fff; color: # 000; width: 50%;)

The above styles will be applied to all fields and forms of the Contact Form 7 plugin as indicated by the .wpcf7 selector. Learn more about selectors.

Style for a specific field

When creating any field, you can give it an identifier or class:

Now in CSS, thanks to the ID, we can only refer to this field:

# very-special-field (color: # f00; border: 1px solid # f00;)

Form style

We've talked about field styles, but how do you add the appearance of the form itself? Let's use the wpcf7 class already known to us, which is added to all plugin forms:

Wpcf7 (background-color: # f7f7f7; border: 2px solid # 0f0;)

Configuring Error Messages

When submitting a form, if a required field is not filled in or has not passed the check, Contact Form 7 will display an error message. These messages can be customized.

Change text

The text of this or that error, notification can be changed. For example, if you submit a form with an empty required field, the message "Field is required." To change the text of this message, open the edit form, the tab "Form Submission Notifications". If you need to change the error text for each field separately, then you should pay attention to the Contact form 7 Custom validation plugin.

Static or floating message?

As they say, it is better to see once than hear a hundred times, because look:

Static message style

Error messages appear below the field and do not disappear until the form is successfully submitted.

Floating message style

Error messages are displayed below the box in a tooltip style. The tooltip disappears when you hover over it or when the focus is in the field to which this tooltip belongs.

Floating style for the desired field

To set a floating style to a specific field, you need to wrap it in a block with the use-floating-validation-tip class:

Floating style for all fields

In order not to wrap each field in a block with the use-floating-validation-tip class, you can "ask" the plugin to do it for us by specifying the html_class attribute with the value use-floating-validation-tip in the form shortcode:

If a non-Ajax dispatch is used (with page reload), then regardless of the settings, the static style of displaying errors will be used.

Long sheet manager with Listo

Let's say we need to make a contact form where the user is prompted to select his location using a drop-down list. There are about 200 countries in the world and creating such a list will result in torment.

For example:

It is difficult to manage such a "sausage" and the probability of making a mistake is high.

To solve this nonsense, there is a Listo plugin that provides the following lists:

  • Countries - data: countries, data: countries.olympic
  • US structural divisions - data: us_subdivisions.states, data: us_subdivisions.districts
  • Currencies - data: currencies
  • Time zones

Contact Form 7 knows how to work with Listo (or, on the contrary, no one knows this), which in turn works with fields: drop-down list, checkboxes and radio buttons. Thanks to such a bundle, you will not have to painfully edit long lists, but you can use short predefined parameters.

How to manage parameters of a long list

For example, we decided to display a list of countries, for this we need a dropdown tag:

The list is still empty, we have not passed any parameters. Let's add them:

Just one parameter and we became vegans - no "sausage" with a list of countries - Listo did it for us.

Additional settings

Each form can be specified additional. options in the "Advanced Settings" tab. Let's consider all such settings:

Subscribers Only Mode

Subscribers_only: true

This mode (available since CF7 v7 4.9) allows you to display the form for registered users only. Unregistered users will see the message "This form is available for registered users only." and, accordingly, will not be able to fill out and submit the form. A great way to get rid of spam if you only need to accept emails from authorized users.

Demo mode

Demo_mode: on

When using this code, the form will switch to demo mode. In this mode, the contact form will skip the mail submission process and simply display "completed successfully" as a response message.

Skip email

Skip_mail: on

The skip_mail parameter works much the same as demo_mode, but skip_mail only skips sending messages. Unlike demo_mode, skip_mail does not affect other actions such as saving messages with Flamingo.

Forced field validation

Acceptance_as_validation: on

By default, fields such as checkboxes do not generate errors. This parameter allows you to apply validation rules to checkboxes, the same as for other fields. For example, if you created a checkbox in which the user must check the box of what gender he is, and the user did not select anything, the plugin will display common mistake"Not all fields are filled in." If you apply this parameter, then in addition to the general message, the user will see the message individually for this checkbox.

Prevent saving messages

Do_not_store: true

This parameter tells message storage modules such as Flamingo not to save messages through this contact form.

JavaScript code execution

This functionality comes in handy when you need to track user behavior. Tracking via Google Analytics or other statistics systems can be attached to these hooks (see above).

on_sent_ok: "alert (" sent ok ");" on_submit: "alert (" submit ");" on_sent_ok passed JavaScript will be executed after successful form submission. on_submit The passed JavaScript will be executed when the submit button is clicked.

Hiding Contact Form 7 after successful message submission

We have a customized and working form. And it is necessary that when the user clicks on the "Send" button and the letter leaves us, the form disappears, and the text "Sent!" Appears in its place.

This is done simply: for this in additional settings plugin add a line like this:

Document.addEventListener ("wpcf7mailsent", function (event) (jQuery ("# ​​contactform"). Hide ();), false);

where contactform is the ID of the form you want to hide. Instead of #contactform, you can specify another element (form) HTML selector that you want to hide.

How to combine similar options in a select tag into separate groups? This functionality can provide html tag optgroup, but by default the Contact Form 7 plugin cannot do this. Let's consider how to solve this non-standard task for a plugin.

Method 1 using JavaScript

This method was spied on codepen.io and slightly revised. The essence of the method is that JavaScript "reads the structure of the select tag and converts it into the desired format. The example will consider the field for selecting the engine:

Form template:

The field name was chosen engines, so in the email template we use the tag so that the value selected by the user is sent to the mail.

Adding JavaScript

JQuery (document) .ready (function ($) (var selectEngines = $ ("select"); var foundin = $ ("option: contains (" optgroup- ")", selectEngines); $ .each (foundin, function ( value) (var updated = $ (this) .val (). replace ("optgroup-", ""); $ (this) .nextUntil ("option: contains (" endoptgroup ")"). wrapAll (" ");)); $ (" option: contains ("optgroup-"), option: contains ("endoptgroup") ", selectEngines) .remove ();));

This code is implemented in jQuery. You should insert it into the js file of the theme or create a new js and connect it. Since the name of the tag was engines, in this code we specify exactly it, that is, select.

Original html code of select field

The processed html code of the select field

If the user has JavaScript is disabled then the box will display all option. That is, even options that should have been converted to an optgroup tag will become visible as regular options.

After installing the Contact Form 7 plugin and displaying the form on the page, it looks something like this.

Agree, not very expressive. But its appearance can be easily corrected.

If you know how to change / add CSS styles you probably want to start with styling fields.

Wpcf7 input, .wpcf7 input, .wpcf7 textarea (/ * here styles: color, background, font, size, borders, etc. * /)

Then, to enhance the blend with your theme, you can tweak the styles. for the whole form.

Wpcf7 (/ * styles here: color, background, font, size, borders, etc. * /)

How do I style a specific field only? Let's say you want to change the styles for the optional field ‘ Theme'Which is present in the default form after plugin activation.

You just need to add the ID for the required field in the form template.

Then you can write your own CSS styles.

# fb-subject (/ * styles here: color, background, font, size, borders, etc. * /)

To make a simple yet pleasing form design feedback, you don't need to be a web programmer or computer geek at all. You can easily find all the necessary information on the Internet along with examples and explanations.

Here's another plugin Form Styles For Contact Form 7 with simple yet cute preset styles.

Simple and clean contact form - Contact Form Clean and Simple- with Bootstrap markup, Google captchas and spam filters. By the way, pay attention, a rather popular plugin.

If you search the internet yourself, I'm sure you will find numerous templates and styles for Contact Form 7.

But if you spend a little time styling, you can create a unique look for your contact form, and you will not only be proud of it, but also receive a large number of messages from your audience, because they will be pleased to write to it and send you letters. 🙂

DOM events

By monitoring DOM events, you can do anything at the right time while working with the form. For example, after successfully submitting a form, say "Thank you" in a pop-up window or redirect the user to another page.

List of form events

Wpcf7invalid Fires when the form has been successfully submitted to the server, but mail was not sent because there were fields with invalid input. wpcf7spam Fires when a form has been successfully submitted to the server, but mail was not sent because possible spam activity has been detected. wpcf7mailsent Fires when the form has been successfully submitted to the server and mail sent to the addressee. wpcf7mailfailed Fires when a form has been successfully submitted to the server, but failed to send mail... This may be due to the fact that the mail server does not work on the hosting. wpcf7submit Fires when the form has been successfully submitted to the server, regardless of other incidents. We pressed the "Submit" button - this action worked. wpcf7beforesubmit Triggered before the wpcf7submit event, which allows you to perform any manipulations with formData - form data that will be sent to the server. The event was added in CF7 v4.9.

The code from the examples below should be used wherever the form is displayed. If your form is displayed on all pages of the site, then a good solution would be to place the code in the footer.php file, since this template is used on all pages of the site.

Examples for the wpcf7submit event

The code below is a simple example of registering an event handler. In this example, the function listens for the wpcf7submit event from the container with the wpcf7 class and simply issues a warning when it occurs, that is, when you click the "Send" button, it immediately calls the message "Opachki, they are trying to send me ... to Magadan!". Note that the element with the wpcf7 class is a DIV with a form inside, the plugin generates all this on its own. If you have multiple forms on the page, the code will work only for the first found form... Of course, you replace the unnecessary alert () with a more useful action, for example, a nice animation for submitting a form.

// We are looking for a block with a form that has the wpcf7 class (all divs with a form have it) var wpcf7Elm = document.querySelector (". Wpcf7"); // Monitor the wpcf7submit event for the selected block wpcf7Elm.addEventListener ("wpcf7submit", function (event) (alert ("Opachki, they are trying to send me ... to Magadan!"); // Or something more useful), false) ;

If you want to monitor some specific form (below in the article there will be alternative solutions, more rational), then indicate the container ID:

// Looking for a unique block with a form by its ID var wpcf7Elm = document.querySelector ("# wpcf7-f92-p95-o1"); // Monitor the wpcf7submit event here, as in the previous example.

The examples above are designed to work with one form. If there are several forms on the page and you need to monitor the wpcf7submit event (or others) for everyone, then we hang the event not on a separate block, but on the entire document:

Document.addEventListener ("wpcf7submit", function (event) (alert ("Someone submitted a form! Which one? I don't know yet.");), False);

How to track entered data into fields

The custom data is passed to the event handler as the detail.inputs property of the event object. The detail.inputs data structure is an array of objects, and each object has name and value properties. Let's say the form has 4 fields. We use the code:

Document.addEventListener ("wpcf7submit", function (event) (var inputs = event.detail.inputs; console.log (inputs);), false);

When you click the "Submit" button, the data structure will be displayed in the browser console:

We have access to the name of each form field (the field name is indicated in the admin panel in the field tag and is a required attribute) and its value.

You can iterate over each field and react to a certain one like this:

Document.addEventListener ("wpcf7submit", function (event) (var inputs = event.detail.inputs; // Look for a field named your-name and abuse the alert "when finding the for field (var i = 0; i< inputs.length; i++) { if ("your-name" == inputs[i].name) { alert(inputs[i].value); break; } } }, false);

There are other properties of the event object that you can use in your handler.

Detail.contactFormId The ID of the contact form. This ID can be seen in the admin panel in the address bar when editing the form or in the form's shortcode itself. detail.pluginVersion Version of the Contact Form plugin 7. detail.contactFormLocale Language code of the form. For example, ru_RU. detail.unitTag Contact form unit tag. Each form has its own, for example wpcf7-f92-p95-o1. detail.containerPostId ID of the post containing the form.

You can view all the data like this:

Document.addEventListener ("wpcf7submit", function (event) (console.log (event.detail);), false);

How to handle a specific shape

For example, if you only want to do something with a specific contact form (ID = 123), use the detail.contactFormId property as shown below:

Document.addEventListener ("wpcf7submit", function (event) (if ("123" == event.detail.contactFormId) (alert ("Contact form with ID = 123."); // Do something else)), false);

Fighting spam with Akismet

How to deal with spam in the Contact Form 7 plugin? Several mechanisms are provided, but only a couple are popular: reCAPTCHA and Akismet.

How do I install and configure Akismet? When you install WordPress, the Akismet plugin is installed automatically, you just need to activate it. If for some reason it is not there, then these links will help you:

After activating the plugin, a message will appear prompting you to activate your account:

When you click on the button, you will be taken to the plugin settings page:

For Akismet to work, you need to specify the API key in the plugin settings. If it is not there, then click the "Get API Key" button and follow the instructions:

  • Registration for off. plugin site using wordpress.com account
  • Choosing a tariff plan (there is a free one)
  • Adding a site to the admin panel of the service by clicking the "Activate this site" button

This is a simple and quick process. After activating the site, a redirect will occur back to the admin panel of your site with ready-made settings, they need to be saved:

In order for Akismet to start checking the field, you need to specify when it is generated by what rule to check, for example:

Akismet: author Add this parameter to the username input field.
Example: akismet: author_email Add this parameter to the user email field.
Example: akismet: author_url Add this parameter to the field for entering a link from the user.
Example:

It is recommended to use the akismet: value parameter for all fields that allow for this check. Based on the collected data, Akismet will decide whether it is spam or not, so completeness is essential.

Contact Form 7 has several types of notification design:

Green frame at the notification Message sent successfully Yellow frame at the notification Some fields are filled with an error, the field has not been validated Orange frame at the notification Message is marked as spam Red border at the notification Message sending failed

Now you can test the Akismet protected form by typing "viagra-test-123" instead of the username. A message with such data will be marked as spam and will not be sent by email.

Restricting access to the administration panel

Initially, the Contact Form 7 tab is available to all users with the contributor role and above. Only editors and administrators can edit forms. How do I change access rights to forms?

Access parameters are changed using constants that are written in the engine root in the wp-config.php file, for example:

Define ("WPCF7_ADMIN_READ_CAPABILITY", "manage_options"); define ("WPCF7_ADMIN_READ_WRITE_CAPABILITY", "manage_options");

By default, site admins and super admins have the manage_options right. Therefore, this example will give access to the list of forms and the ability to edit them only for users with these roles. Other roles will not see the plugin tab.

WPCF7_ADMIN_READ_CAPABILITY Minimum role or ability to access the admin panel, that is, display the menu and list of forms.
Default: edit_posts WPCF7_ADMIN_READ_WRITE_CAPABILITY Minimum Role or Capability for Form Editing. This parameter must be stricter or the same as WPCF7_ADMIN_READ_CAPABILITY. This is explained by the fact that you cannot edit forms without having access to the admin panel.
Default: publish_pages

For a better understanding of how this works, take a look at the code (CF7 v4.9.1, capabilities.php file) using these constants:

Add_filter ("map_meta_cap", "wpcf7_map_meta_cap", 10, 4); function wpcf7_map_meta_cap ($ caps, $ cap, $ user_id, $ args) ($ meta_caps = array ( "wpcf7_edit_contact_form" => WPCF7_ADMIN_READ_WRITE_CAPABILITY, "wpcf7_edit_contact_forms" => WPCF7_ADMIN_READ_WRITE_CAPABILITY, "wpcf7_read_contact_forms" => WPCF7_ADMIN_READ_CAPABILITY, "wpcf7_delete_contact_form" => WPCF7_ADMIN_READ_WRITE_CAPABILITY, " wpcf7_manage_integration "=>" manage_options "," wpcf7_submit "=>" read ",); $ meta_caps = apply_filters (" wpcf7_map_meta_cap ", $ meta_caps); $ caps = array_diff ($ caps); array_keys ($ meta_caps [$ cap])) ($ caps = $ meta_caps [$ cap];) return $ caps;)

From the code, you can see that the array of possibilities passes through the wpcf7_map_meta_cap filter, and contains the following data:

By default Array (=> publish_pages => publish_pages => edit_posts => publish_pages => manage_options => read) After changing, for example, using constants Array (=> manage_options => manage_options => manage_options => manage_options => manage_options = > read)

Thanks to the wpcf7_map_meta_cap filter, we can change this array. This way saves us from editing the wp-config.php file, but we have to write code, for example, in the functions.php file:

Add_filter ("wpcf7_map_meta_cap", "change_wpcf7_map_meta_cap"); function change_wpcf7_map_meta_cap ($ meta_caps) (// New feature value $ replace_caps = array ("wpcf7_edit_contact_form" => "manage_options", "wpcf7_edit_contact_forms" => "manage_options", "wpcf7_formopcontact7> manage_options ",); return array_replace ($ meta_caps, $ replace_caps);)

Design of checkboxes and radio buttons

Contact Form 7 lines up checkboxes and radio buttons by default. But this can be changed using the tag settings of these fields and simple CSS rules.

This is what the default checkboxes look like:

But if you pass the label_first parameter to the checkbox tag, the display of the label relative to the checkbox will change to the opposite:

To stack the checkboxes in a column, add a line of styles to the theme's CSS file:

Span.wpcf7-list-item (display: block;)

To line up the checkboxes as a table, add a line of styles to the theme's CSS file (optionally using the label_first parameter):

Span.wpcf7-list-item (display: table-row;) span.wpcf7-list-item * (display: table-cell;)

Loading JavaScript and CSS as needed

By default, Contact Form 7 loads JavaScript and CSS on all pages of the site, regardless of where the form is used. Technically, the plugin cannot work otherwise, but it can be "prompted".

Example 1 - completely disable JavaScript and CSS and enable where needed

Step 1 - disable JavaScript and CSS on all pages of the site

There is a WPCF7_LOAD_JS constant with a default value of true, which is defined in the plugin code and is responsible for loading JavaScript on all pages of the site. It can be overridden by inserting the following code into the wp-config.php file:

Define ("WPCF7_LOAD_JS", false);

This code will cancel the loading of plugin scripts.

And the same constant is for WPCF7_LOAD_CSS styles, which works on the same principle - it cancels loading of plugin styles:

Define ("WPCF7_LOAD_CSS", false);

From plugin version 3.9 and above, you can disable loading JavaScript and CSS via hooks in functions.php:

Add_filter ("wpcf7_load_js", "__return_false"); add_filter ("wpcf7_load_css", "__return_false");

But now we have another problem - on the page with the form, the styles and scripts of the plugin are not loaded, and the functionality and appearance are corrupted. We need a mechanism that would solve the problem.

Step 2 - uploading files on form pages

For example, we have a Contact page with a form. The contact.php file is responsible for displaying the page. Then, let's use the code:

If (function_exists ("wpcf7_enqueue_scripts")) (wpcf7_enqueue_scripts ();) if (function_exists ("wpcf7_enqueue_styles")) (wpcf7_enqueue_styles ();)

This construct must be placed in the contact.php file before calling the wp_head () function. This is a recommendation from the plugin developer.

Example 2 - disabling scripts and styles wherever NOT needed

There is a more flexible method that allows you to specify on which pages to include scripts. This code needs to be inserted into functions.php:

Option 1:
## Disable styles, plugin scripts everywhere except for the contacts page add_filter ("wp", "cf7_disable_css_js"); function cf7_disable_css_js () (if (! is_page ("contacts")) (add_filter ("wpcf7_load_js", "__return_false"); add_filter ("wpcf7_load_css", "__return_false");))
Option 2:
## Disable styles, plugin scripts everywhere except for the contacts page add_action ("wp_print_styles", "my_deregister_javascript", 100); function my_deregister_javascript () (if (! is_page ("contacts")) (wp_deregister_script ("contact-form-7"); // disable plugin scripts wp_deregister_style ("contact-form-7"); // disable plugin styles))

Example 3 - including scripts only when using the form shortcode

First, we unplug the JS and CSS, and then plug it back in only when the form's shortcode is triggered. Thus, the files will be included only on those pages where there is a form shortcode.

Function wpcf7_remove_assets () (add_filter ("wpcf7_load_js", "__return_false"); add_filter ("wpcf7_load_css", "__return_false");) add_action ("wpcf7_inf_c." function wpcf7_add_assets ($ atts) (wpcf7_enqueue_styles (); return $ atts;) add_filter ("shortcode_atts_wpcf7", "wpcf7_add_assets");

The code can be styled as a plugin or inserted into the theme's functions.php.

Tracking Forms with Google Analytics

There is an easy way to track form events through Google Analytics.

First, make sure you have the Google Analytic code, which looks something like this:

If you have the Analytics code or after installing it, you can send data to the system, which can then be monitored in the Google Analytics admin panel. Read more about this in the official documentation on event tracking.
For example, you need to track the submission of a form, for this you need to execute the following code:

Ga ("send", "event", "Contact Form", "submit");

The final step is to insert this JavaScript snippet into the HTML header ( ) of each page. You can edit your theme's header.php template for this, or you can use the wp_head functions.php hook on the hook.

And this is how you can track the successful submission of each individual form:

Document.addEventListener ("wpcf7mailsent", function (event) (if ("123" == event.detail.contactFormId) (ga ("send", "event", "Contact Form 123", "submit");) if ("253" == event.detail.contactFormId) (ga ("send", "event", "Contact Form 253", "submit");)), false);

Now, upon successful submission of the form, you will see this event in the Google Analytics admin panel (Behavior -> Events -> Overview). Perhaps the data will not appear there immediately after the event, but after 24-48 hours.

Selecting a recipient in the form

Let's imagine that you have a small web studio with staff: SEO, salesperson and technical support. How to send information to one of them personally using one form? The select field (drop-down list) will come to the rescue! The problem is solved in two stages.

Stage 1 - adding a tag to the form template:

Stage 2 stage - inserting a tag into the "To" field, which, when sending a letter, will take the mail selected by the user from our drop-down list and substitute it into the field.

This method has a serious drawback. Take a look at the code after transforming our dropdown tag:

As you can see, email addresses are "stored" in clear text. The ubiquitous spammers can take advantage of this. But not after a little trick ... Let's update our tag like this:

Here we passed the parameter through the so-called pipe (forward slash) according to the rule name | value. As a result, we got the following html structure in the output:

As you can see, in the form, the user selects one of the items, and the plug-in when sending the letter itself takes the value based on the name of the selected item.

Let's complicate the task even more ...

Imagine a situation when you need to send a letter to a selected addressee, for example, SEO, and another copy of the letter to the site manager for control.

In previous articles, we considered that Contact Form 7 can send two letters, and for each recipient, you can set a separate template.

So, the first copy comes to SEO and he understands what the message is about. But the manager does not understand which specialist the letter was addressed to, because he may not fully understand the topic or not remember all the mailing addresses of the specialists. There is a need for a letter template to use not only the value of the field (in our case, the email address), but also the heading of the item (name of the specialist)? To do this, the plugin provides us with the [_raw_ (field name)] tag, where (field name) is the name of our field. To summarize the use of tags:

The value of the field, which in the email template is converted to the value of the selected item (the email address in our example, that is [email protected]) [_raw_your-recipient] the name of the field, which in the letter template is converted to the name (title) of the selected item (the name of the specialist in our example, that is, Seoshnik)

If this functionality is not needed, then it can be disabled by entering the following code into the wp-config.php file:

Define ("WPCF7_USE_PIPE", false);

Adding Cc, Bcc and other email headers

Contact Form 7 in the tab with setting the email template has a field for sending additional headers (Additional Headers) according to the rule name-header: value. Each heading should start on a new line.

Consider the most popular ones - Reply-To, Cc and Bcc, read about the rest on Wikipedia.

Reply-To The name and address where replies to this letter should be addressed. For example, you asked the user to enter their email address in the form. Use it so that the email client immediately knows which email to send the response to. Cc (from the English carbon copy) contains the names and addresses of the secondary recipients of the letter to which the copy is sent. Bcc (from English blind carbon copy) contains the names and addresses of the recipients of the letter, whose addresses should not be shown to other recipients.

Contact Form 7 in your language

Contact Form 7 automatically uses the translation of the language that you use in the admin area. The language is changed in Settings -> General -> Site language (drop-down list). But this will change the language for the entire site. But what to do when your authors speak different languages?

To do this, the developers suggest using the Bogo plugin, which for each user makes it possible to switch the admin panel language. After activation, a language switch will appear in the toolbox next to your nickname.

Special email tags

Contact Form 7 supports a few specific tags that you might need when working with a form. For example, in the letter indicate the IP of the sender and the link of the page where the form was filled out. Special tags can be used in email templates or other form fields.

Submit tags

[_remote_ip] This tag will be replaced with the user's IP. [_user_agent] This tag will be replaced with the User Agent of the user's browser. User Agent is a string that web browsers use as their name, it contains not only the name of the browser, but also the version of the operating system and other parameters. [_url] This tag will be replaced with the URL of the page from which the form was submitted. [_date] Will be replaced by the date the form was submitted. [_time] Will be replaced at the time the form is submitted. [_invalid_fields] This tag is replaced by the number of form fields with invalid input. Use in notification templates. [_serial_number] Will be replaced with the sequence number of the stored message. The Flamingo 1.5+ plugin must be installed, described below.

Post tags

These tags will only work in the post content. If the form in a modal window, sidebar, footer or header is embedded in the theme template, that is, outside the post content, they will not work.

[_post_id] Will be replaced with the post ID in the content of which the form is displayed. [_post_name] Will be replaced with the name (slug) of the post from which the form was submitted. [_post_title] Will be replaced with the title (title) of the post from which the form was submitted. [_post_url] Will be replaced with the link (url) of the post from which the form was submitted. [_post_author] Will be replaced with the name of the author of the post from which the form was submitted. [_post_author_email] Will be replaced with the email of the author of the post from which the form was submitted.

Site tags

[_site_title] Will be replaced by the site name (specified in General Settings). [_site_description] Will be replaced by the site description (specified in General Settings). [_site_url] Will be replaced with the site address (specified in General Settings). [_site_admin_email] Will be replaced with the site's e-mail address (specified in General settings).

User tags

These tags provide information about the current registered user.

[_User_ *] tags only work when Sender has an account and is logged in. If the form is submitted by an unauthorized user, then these tags will return an empty result and there will be no sense from them. It is recommended to enable the "" mode so that the form is displayed only for registered users.

If you want to use these tags and do not need to use the subscribers_only: true option, you need to enable the nonce option. If all this is not done, the data of authorized users will be reset via WP REST API and the specified tag will be skipped (replaced with an empty string).

[_user_login] Will be replaced with the username. [_user_email] Will be replaced with the user's email. [_user_url] Will be replaced with the URL of the user's site. [_user_first_name] Will be replaced with the username. [_user_last_name] Will be replaced with the user's last name. [_user_nickname] Will be replaced with the user's nickname. [_user_display_name] Will be replaced with the user's display name.

Saving sent messages with Flamingo

// You can do the same using the filter add_action ("wpcf7_autop_or_not", "__return_false"); WPCF7_USE_PIPE When the constant value is false (default is true), Contact Form 7 starts to accept | as a normal character. WPCF7_ADMIN_READ_CAPABILITY Minimum role or ability to access the admin panel.
Default: edit_posts... WPCF7_ADMIN_READ_WRITE_CAPABILITY Minimum Role or Capability for Form Editing. By default publish_pages. This parameter must be stricter or the same as WPCF7_ADMIN_READ_CAPABILITY. This is because you cannot edit forms without access to the administration panel. WPCF7_CAPTCHA_TMP_DIR Defining this constant will override the folder path for temporary CAPTCHA files. WPCF7_CAPTCHA_TMP_URL Defining this constant will override the folder reference for temporary CAPTCHA files. WPCF7_UPLOADS_TMP_DIR Defining this constant will override the temporary folder path for downloaded files. WPCF7_VERIFY_NONCE

Tells the plugin whether to check nonce (security code) or not. Since plugin version 4.9, this constant has become false, that is, "do not check". You can return the check by setting the constant value to true or using a hook

Add_filter ("wpcf7_verify_nonce", "__return_true");

Redirecting to another address after submitting the form

When you need to redirect the user to a page after a successful form submission, for example, with a thank you or a gift, use the JavaScript hook:

See DOM Events for an explanation of how this works.

WordPress spam blacklist for filtering forms

If you suffer from an influx of spam or unwanted messages, and CAPTCHAs or Akismet cannot cope, then the "Black List" functionality built into the engine can help out.

The blacklist is located in the admin panel along the Settings -> Discussion path.

If a message sent via Contact Form 7 contains any of these words in its text, author name, URL, e-mail address or IP address, it will be marked as spam and will not be sent. Each word or IP on a new line. Search by substring is used, that is, by the word "buy" will be found "buy".

How do I find out the IP address from which spam comes through the Contact Form 7? The easiest way is to use the special tag [_remote_ip]. This tag is inserted into the email template and will be replaced with the sender's IP address when the email is sent.

Contact Form 7 form design

I often cite the html code of one or another field in Contact Form 7. You can see which classes the plugin adds to the fields by default. And now we will briefly go over how to set custom classes for form fields.

What CSS to edit to change the appearance of the form?

All styles that are responsible for the external form feed are stored in the plugin file contact-form-7 / includes / css / styles.css. It is not a good idea to change this file, as updating the plugin will replace the file and you will lose all changes. The same goes for public themes, which are also updated like plugins.

Therefore, to change styles, you need to select a style file that will not update. This can be a child theme stylesheet. Alternatively, you can use the theme settings, which allow you to insert CSS code into a special field.

If you have your own theme, you can change (interrupt) the Contact Form 7 styles in the theme styles.

Field Styles in Contact Form 7

The plugin supports many types of fields, but the most common type of field is text. To set a style for such a field, you need to refer to it by type:

Wpcf7 input (background-color: #fff; color: # 000; width: 50%;)

We often use more than one field in the form, so let's add properties to several at once:

Wpcf7 input, .wpcf7 input, .wpcf7 textarea (background-color: #fff; color: # 000; width: 50%;)

The above styles will be applied to all fields and forms of the Contact Form 7 plugin as indicated by the .wpcf7 selector. Learn more about selectors.

Style for a specific field

When creating any field, you can give it an identifier or class:

Now in CSS, thanks to the ID, we can only refer to this field:

# very-special-field (color: # f00; border: 1px solid # f00;)

Form style

We've talked about field styles, but how do you add the appearance of the form itself? Let's use the wpcf7 class already known to us, which is added to all plugin forms:

Wpcf7 (background-color: # f7f7f7; border: 2px solid # 0f0;)

Configuring Error Messages

When submitting a form, if a required field is not filled in or has not passed the check, Contact Form 7 will display an error message. These messages can be customized.

Change text

The text of this or that error, notification can be changed. For example, if you submit a form with an empty required field, the message "Field is required." To change the text of this message, open the edit form, the tab "Form Submission Notifications". If you need to change the error text for each field separately, then you should pay attention to the Contact form 7 Custom validation plugin.

Static or floating message?

As they say, it is better to see once than hear a hundred times, because look:

Static message style

Error messages appear below the field and do not disappear until the form is successfully submitted.

Floating message style

Error messages are displayed below the box in a tooltip style. The tooltip disappears when you hover over it or when the focus is in the field to which this tooltip belongs.

Floating style for the desired field

To set a floating style to a specific field, you need to wrap it in a block with the use-floating-validation-tip class:

Floating style for all fields

In order not to wrap each field in a block with the use-floating-validation-tip class, you can "ask" the plugin to do it for us by specifying the html_class attribute with the value use-floating-validation-tip in the form shortcode:

If a non-Ajax dispatch is used (with page reload), then regardless of the settings, the static style of displaying errors will be used.

Long sheet manager with Listo

Let's say we need to make a contact form where the user is prompted to select his location using a drop-down list. There are about 200 countries in the world and creating such a list will result in torment.

For example:

It is difficult to manage such a "sausage" and the probability of making a mistake is high.

To solve this nonsense, there is a Listo plugin that provides the following lists:

  • Countries - data: countries, data: countries.olympic
  • US structural divisions - data: us_subdivisions.states, data: us_subdivisions.districts
  • Currencies - data: currencies
  • Time zones

Contact Form 7 knows how to work with Listo (or, on the contrary, no one knows this), which in turn works with fields: drop-down list, checkboxes and radio buttons. Thanks to such a bundle, you will not have to painfully edit long lists, but you can use short predefined parameters.

How to manage parameters of a long list

For example, we decided to display a list of countries, for this we need a dropdown tag:

The list is still empty, we have not passed any parameters. Let's add them:

Just one parameter and we became vegans - no "sausage" with a list of countries - Listo did it for us.

Additional settings

Each form can be specified additional. options in the "Advanced Settings" tab. Let's consider all such settings:

Subscribers Only Mode

Subscribers_only: true

This mode (available since CF7 v7 4.9) allows you to display the form for registered users only. Unregistered users will see the message "This form is available for registered users only." and, accordingly, will not be able to fill out and submit the form. A great way to get rid of spam if you only need to accept emails from authorized users.

Demo mode

Demo_mode: on

When using this code, the form will switch to demo mode. In this mode, the contact form will skip the mail submission process and simply display "completed successfully" as a response message.

Skip email

Skip_mail: on

The skip_mail parameter works much the same as demo_mode, but skip_mail only skips sending messages. Unlike demo_mode, skip_mail does not affect other actions such as saving messages with Flamingo.

Forced field validation

Acceptance_as_validation: on

By default, fields such as checkboxes do not generate errors. This parameter allows you to apply validation rules to checkboxes, the same as for other fields. For example, if you have created a checkbox in which the user must check the box of what gender he is, but the user has not selected anything, the plugin will give a general error "Not all fields are filled in". If you apply this parameter, then in addition to the general message, the user will see the message individually for this checkbox.

Prevent saving messages

Do_not_store: true

This parameter tells message storage modules such as Flamingo not to save messages through this contact form.

JavaScript code execution

This functionality comes in handy when you need to track user behavior. Tracking via Google Analytics or other statistics systems can be attached to these hooks (see above).

on_sent_ok: "alert (" sent ok ");" on_submit: "alert (" submit ");" on_sent_ok passed JavaScript will be executed after successful form submission. on_submit The passed JavaScript will be executed when the submit button is clicked.

Hiding Contact Form 7 after successful message submission

We have a customized and working form. And it is necessary that when the user clicks on the "Send" button and the letter leaves us, the form disappears, and the text "Sent!" Appears in its place.

This is done simply: for this, in the additional settings of the plugin, add the following line:

Document.addEventListener ("wpcf7mailsent", function (event) (jQuery ("# ​​contactform"). Hide ();), false);

where contactform is the ID of the form you want to hide. Instead of #contactform, you can specify another element (form) HTML selector that you want to hide.

How to combine similar options into separate groups in the select tag? This functionality can be provided by the html optgroup tag, but by default the Contact Form 7 plugin does not. Let's look at ways to solve this non-standard task for a plugin.

Method 1 using JavaScript

This method was spied on codepen.io and slightly revised. The essence of the method is that JavaScript "reads the structure of the select tag and converts it into the desired format. The example will consider the field for selecting the engine:

Form template:

The field name was chosen engines, so in the email template we use the tag so that the value selected by the user is sent to the mail.

Adding JavaScript

JQuery (document) .ready (function ($) (var selectEngines = $ ("select"); var foundin = $ ("option: contains (" optgroup- ")", selectEngines); $ .each (foundin, function ( value) (var updated = $ (this) .val (). replace ("optgroup-", ""); $ (this) .nextUntil ("option: contains (" endoptgroup ")"). wrapAll (" ");)); $ (" option: contains ("optgroup-"), option: contains ("endoptgroup") ", selectEngines) .remove ();));

This code is implemented in jQuery. You should insert it into the js file of the theme or create a new js and connect it. Since the name of the tag was engines, in this code we specify exactly it, that is, select.

Original html code of select field

The processed html code of the select field

If the user has JavaScript is disabled then the box will display all option. That is, even options that should have been converted to an optgroup tag will become visible as regular options.

It so happened that the styles that are used by the Contact Form 7 plugin by default are not at all attractive. I would even say that they are just awful. In this regard, each time activating this plugin on a new site, you have to bring the beauty manually, and so that this whole thing would not be a routine, I created an export form and prescribed styles for it that can be downloaded and copied from this site. Below is the export file itself:

After importing the forms, do not forget to replace on the form tab "Letter" in field "To whom" [email protected] to your Email, in the field "From whom" a place [email protected] enter the email address from your domain. Also replace to your full path to the logo, that is, as an example, specify:

Import the export file in the usual way WordPress:

CSS Styles:

/ * ////////////////////////////// * / / * Contact Form 7 * / / * /////// /////////////////////// * / div.wpcf7-response-output (margin-top: -30px;) span.wpcf7-not-valid-tip (margin-top: -14px; margin-bottom: -10px; text-align: center;) span.wpcf7-not-valid-tip (color: # a01414; font-size: 1em; / * font-weight: normal ; * / display: block; font-weight: 700! IMPORTANT;) @media screen and (max-width: 768px) (span.wpcf7-not-valid-tip (margin-bottom: 15px;) input.wpcf7-form -control.wpcf7-text (max-height: 30px;)) / * Loader * / / * div.wpcf7 .ajax-loader (margin-left: auto; vertical-align: middle; margin-right: auto; position: inherit; padding-right: 51%; background-repeat: no-repeat; background-position-x: right; margin-top: -31px;) * / / * Styles of misspelled boxes for forms that are located on a darkened background : * / .wpcf7-response-output.wpcf7-display-none.wpcf7-validation-errors (color: aliceblue; font-weight: 800;) span.wpcf7-not-valid-tip (font-weight: 900 ; background-color: antiquewhite; ) textarea (height: 150px! Important;) / * Hiding broths in the error alert * / .screen-reader-response ul (display: none;) .wpcf7-response-output.wpcf7-display-none.wpcf7-mail-sent -ok (display: none! important;) .wpcf7-response-output.wpcf7-display-none.wpcf7-validation-errors (display: none! important;) / * Error message - white letters * / .screen-reader -response (color: white; margin-bottom: 10px;) / * Error message - bottom message indent * / / * span.wpcf7-form-control-wrap.textarea-102 span.wpcf7-not-valid-tip ( margin-top: -30px;) * / / * Error message - margin of bottom message * / .wpcf7-response-output.wpcf7-display-none.wpcf7-validation-errors (margin-top: -60px;) / * Formatting text in INPUT * / input.wpcf7-form-control, textarea # TextareaJA, input.wpcf7-form-control.wpcf7-submit (font-family: "Open Sans"; font-size: 15px; / * font-size : 20px; * / line-height: 30px; font-weight: 700;)) / * Appearance of the submit button * / input.wpcf7-form-control.wpcf7 -submit (margin-top: -15px; ) / * ////////////////////////////// * / / * Contact Form 7 END * / / * ///// ///////////////////////// * / / * NEW 2018-06-04 * / / * Styles when inserting the cursor to stroke inputs * / form. wpcf7-form input: focus, form.wpcf7-form textarea: focus, form.wpcf7-form input: focus (border-color: # 709242;) / * Center the ContactForm7 scaling apploader * / span.ajax-loader (margin-left : auto! important; margin-right: auto! important; float: inherit! important; width: 15px! important; display: block! important; margin-top: 10px! important; margin-bottom: -15px! important;) / * Google ReCapcha - center * / .wpcf7-form-control-wrap (width: 100%;) .wpcf7-form-control.g-recaptcha.wpcf7-recaptcha (margin-top: -28px; margin-left: auto; margin-right: auto; / * margin-right: 21px; * / width: 300px;) div # recapcha-popups .wpcf7-form-control-wrap (padding-top: 25px; margin-left: -11px; padding- bottom: 38px;) / * Placeholders - center * / span.wpcf7-form-control-wrap input # Email, span.wpcf7-form-con trol-wrap input # PhoneJA, input.wpcf7-form-control.wpcf7-text.wpcf7-validates-as-required (text-align: center; ) / * Make the submit button pretty * / input.wpcf7-form-control.wpcf7-submit (color: #ffffff; background: # 5a8f2b; font-weight: 600; border: 2px dashed #ffffff; margin-top: -25px ; font-family: FuturaDemiC! Important; padding: 10px 30px; color: #fff; border-radius: 0px; position: relative; / * background: # 42BCE2; * / transition: all .3s ease 0s; ) input.wpcf7-form-control.wpcf7-submit: hover (background: #ffffff; color: # 5a8f2b; / * color: # 5a8f2b; * / border: 2px dashed # 5a8f2b;) / * Center the placeholder of the text box while leaving right alignment when text is printed * / textarea # TextareaJA :: - webkit-input-placeholder (text-align: center;) textarea # TextareaJA: -moz-placeholder (/ * Firefox 18- * / text-align: center;) textarea # TextareaJA :: - moz-placeholder (/ * Firefox 19+ * / text-align: center;) textarea # TextareaJA: -ms-input-placeholder (text-align: center;)

Usefulness:

Filling out the Email tab of the letter:
If you need additional tags to use in a letter, you can always find them here.