Irreparable contact form. How to make a popup contact form for WordPress. Notifications when submitting a form

Flexor 5

This is a contact form creation plugin. It is extremely popular (second only to plugins and in terms of downloads) among users, as it successfully combines ease of use and powerful capabilities for customizing and designing contact forms. I will try to consider all the capabilities of the plugin in as much detail as possible.

1 Unpack the archive.

2 Copy the contact-form-7 folder to /wp-content/plugins/ .

3 Go to the blog admin panel to the “Plugins” tab and activate the plugin.

When activated, the plugin creates a separate menu in the blog admin panel called “”, and also creates a default contact form, which you can see in “Contact Form 7\Forms”:

If you use the proposed “embedding code”, then the form in the blog will be like this:

Of course, the appearance of this contact form will depend on the styles used in your template, but in general this is what it will look like.

It will only take you a couple of minutes to display this simple form. And it is precisely because of this ease of adding a contact form that many users love this plugin.

However, the plugin has a lot of capabilities for creating advanced contact forms of any complexity. But let's start with something simple, by creating your own form, which will be only slightly different from the default form built into the plugin. Click on the “Add new” link:

This will open the initial page for adding a form:

The plugin automatically detects the locale used in the blog, so there is no need to select a language, just click on the "" button. The form designer page will then appear. The first thing you should do here is rename the form title:

The title doesn't matter, it's just there to prevent you from getting confused in your own forms. We set the name of our form, clicked on the “Save” button, and ended up with the “insertion code”:

Now you can paste the proposed code into any of your posts or pages (in “Text” mode, of course) to display a contact form in it. However, it will not differ in any way from the default form, so we will continue to work with the form designer. On the right side of the designer page there is a button "Generate tag", clicking on it will give:

Let's choose, for example, a phone number. The following window will open:

Actually, you don’t have to change anything here at all. Sizes, classes, etc. are minor options and in most cases you do not need to edit them. However, the "" option can be useful as a hint to visitors on how to fill out this field.

For example, we set the following values:

When displaying the contact form, the field will look like this:

When you click on this field, the text entered there will disappear, since it only serves as a hint for filling. But I missed the point of adding the selected tag to the contact form itself. Here's the tag:

You need to insert the following into the left side of the form designer page, where the contact form code itself is located:

You need to create the form code manually, that is, place headings, paragraph tags and line breaks yourself, you should get something like:

We save the form code and end up with this contact form:

Actually, in the same way, you can easily add any tag used by the plugin to your contact form in a couple of minutes. I won’t force you to try each tag manually; I’ll give you their output right away:

1 Text field.

A regular text field, can be used for name, subject, etc.

2 Email.

Used only to enter an e-mail address.

3 URLs.

4 Phone number.

Used only to enter a phone number (numbers and hyphens).

5 Number (spinbox).

Used only to enter a number (can be used to indicate age, number of units ordered, etc.).

6 Number (slider).

It works incorrectly. This numeric slider uses HTML5 to display, which means, firstly, that the slider looks different in different browsers, and secondly, it still doesn't really work. On the plugin support forums, I saw solutions that corrected the operation of this tag, but they did not help me - I could not get this slider to display any numbers. I recommend not using this tag.

7 Date.

Used for date entry only.

8 Text field.

In the Russian translation, this tag was also called “Text field”, but in HTML terminology it is textarea, which, in fact, only means an enlarged text field. Used to enter message text.

9 Drop-down menu.

Used to select an item (or several items) from a drop-down menu. Can be used for anything - from asking about the color of the product being ordered to choosing the gender of a person.

10 Checkboxes.

Used to select one or more items from the proposed options.

11 Radio buttons.

Used to select only one item from the proposed options.

12 Acceptance.

Used to agree to the terms.

13 Question.

Used to answer specified questions (the question is selected randomly from the specified options). Basically, this tag is used as protection against spam. And if spambots can easily answer a numerical question, then questions like “what planet do we live on?” they are unable to answer.

14 CAPTCHA.

Used to display a full captcha. To use this tag, you must install the Really Simple CAPTCHA plugin. The captcha is quite readable, and therefore is easily broken through by advanced spam bots like Khrumer.

15 Sending a file.

Used to send a file. You can specify the maximum size and formats of acceptable files.

16 Send button.

Used to submit contact form data. This is a required tag.

We've sorted out the tags used directly in the contact form. Now let’s look at how to get these same tags from the contact form to your email. Just below the contact form code in the designer there is a template for the letter that will be sent to you, and it is in it that you must make the necessary changes. This is important because filling out this template incorrectly will not allow you to find out what exactly the visitor wrote in your form. As an example, I'll take the phone number tag. Let's say in your contact form it is inserted via code like this:

This means that in the template of the sent letter you need to insert the following code:

The meaning, I think, is clear. In the code of the contact form, and in the letter only the name of this field. The plugin generates digital tag names like , but no one is stopping you from using your own names. And regarding the other tags in the letter template - they are also formed according to the same principle - instead of used, etc.

The texts that the contact form produces can also be edited in the form designer in the “Messages” section:

Frequently asked questions about the plugin:

1 Error like " ", how to fix it?

This means that either the specified form was deleted, or the title of the form was specified incorrectly (the title in the call code is critical for calling the form).

2 In the letter I see tags like instead of text, how can I fix it?

This means that the visitor did not fill out this field. In this case, the tag is not replaced, but is displayed as is.

3 Are there any restrictions when choosing a name for a tag?

Eat. If the WordPress loop uses the name "name", then you cannot use it as the name for the tag. The best way to avoid problems is to add prefixes to names, such as the word "your". There will definitely be no problems with the tag name.

4 Is it possible to notify a visitor via email that their form has been received?

Can. Use the "Addressee 2" option in the form designer:

This option can be used as an answering machine.

5 Is it possible to send a completed form to multiple addresses?

Can. Use the "" field in the "Addressee" option:

Where [email protected] your additional email, to which a copy of the form filled out by the visitor will be sent (the “cc” command sends a hidden copy).

6 Is it possible to display the form not in a post or page?

Yes. Paste the form call code into the text widget.

7 Is it possible to display a form directly using code in template files?

Yes. Use code like:

8 The form is not sent, an error is displayed in a red frame, how can I fix it?

Contact your host, perhaps calling the mail() function is prohibited in PHP.

9 When submitting the form, an error appears in an orange frame, how can I fix it?

An orange frame indicates spam. Caching plugins can cause false alarms of anti-spam protection. Configure your caching plugin to periodically clear cache files (24 hours is enough).

10 The email input field looks different than other fields in the form, how can I fix it?

The plugin uses HTML5 code to enter an email address (instead of), and such code is often not formatted in older templates. You need to edit your template's styles.css to include the necessary code for the input selector.

11 How to insert a user-attached file into an email?

Use the special field "Attached files:" for this.

Really deserves your attention. Unlike many other popular plugins, it doesn't force you to buy any Pro version - all its features are available right away. The popularity of the plugin (over 19 million downloads) is well deserved - with all its functionality, it is extremely easy to set up and is accessible even to novice users of the WordPress engine.

But remember, this is a plugin for creating contact forms, and not a plugin for creating just forms. For all its capabilities, it will not allow you to create an advanced form based on any conditions. Its main purpose is to create contact forms and nothing more. To create dynamic forms, post creation forms and the like, use plugins like Ninja Forms, they are more suitable for this.

If you still have any questions about setting up the plugin, ask in the comments, I will definitely try to help you.


Plugin author: Takayuki Miyoshi
Version in question: 3.9.1 dated 07/31/2014
Current version: 5.1.4 from 08/04/2019
Compatible with WordPress version: 4.9 and higher
Active plugin installations: 5,000,000+
Download plugin version 5.1.4 (total downloads 121,112,956 times)

Did you like the post? Subscribe to updates by or

If the form is located simply on the page, then everything is clear there - error messages and a message after the successful submission of the message appear immediately below the form.

Let's consider what interesting options there may be for events after submitting the CF7 form in a pop-up window, that is, in a pop-up window. I described how to make such a form in the article How to make a feedback form in a pop-up window for WordPress.

We add the code to the Additional settings block of your form.

After successfully sending the message

We display the alert ‘Thank you for your application!’ - primitive and ugly.

On_sent_ok: "alert("Thank you for your request!");"

We redirect to the thank you page

On_sent_ok: "location="http://site.tu/thankyou/";"

Simply closing the pop-up is not the best option; the user may not understand whether everything was successful

On_sent_ok: $.fancybox.close();

We display a pop-up window “Thank you for your order” after successfully sending a message

We display a “Thank you for your order” pop-up window, while the window itself is located in a block with id="popup_msg" , the appearance and styles will need to be designed to match your design so that everything is beautiful + make a ‘Close’ button for the thank you window.

We add this code to the Additional settings block of your CF7 form:

On_sent_ok: "$.fancybox (( href: "#popup_msg" ));"

The window itself looks like this:

Thank you! Close a window

This pop-up window code can be placed anywhere, even in the footer, even under the form, the main advantage is that this window can be called by any other forms and you don’t need to create your own for each form.

And for the “Close window” button, add the following code to the script file:

$(".popup-close-btn").on("click", function() ( $.fancybox.close(); ));

How to download a pdf file after filling out a form using the Contact Form 7 plugin

Open the pdf immediately on the same page

On_sent_ok: "location = "http://site.ua/wp-content/uploads/2016/08/catalog.pdf";"

Open the pdf on a new page

On_sent_ok: "window.open("http://site.ua/wp-content/uploads/2016/08/catalog.pdf", "_blank");"

The method using the on_sent_ok hook is no longer recommended. This feature will be retired by the end of 2017.

Now, to redirect to another page after a successful form submission, you need to use the wpcf7mailsent event

document.addEventListener("wpcf7mailsent", function(event) ( location = "http://example.com/"; ), false);

For example, this option for opening a modal window with id="sentMessage" :

Document.addEventListener("wpcf7mailsent", function(event) ( $("#sentMessage").modal(); ), false);

If you have several forms, then you can create your own events for each form ID:

Document.addEventListener("wpcf7mailsent", function(event) ( var id = event.detail.contactFormId; if (id == 4 || id == 44 || id == 45) ( $.magnificPopup.open(( items : ( src: "#popup_msg" ), type: "inline" ), 0); ) ), false);

id is the form number
$.magnificPopup.open – this example uses Magnific Popup

We create an event for a specific form after successful submission of a message (we use the usual Easy Fancybox)

Many people have difficulties with this point, so I decided to include it in the article.

This script will display the window id="popup_msg" after successfully submitting one of the forms (id == 17754 or id == 17758 or id == 17757):

Document.addEventListener("wpcf7mailsent", function(event) ( var id = event.detail.contactFormId; if (id == 17754 || id == 17758 || id == 17757) ( $.fancybox((href: " #popup_msg")); ) ), false);

Simple code parsing

id == 17754 || id == 17758 || id == 17757 – the window will be shown only for these forms (either-or).

A window with a message about successful sending (you can add it to the code, or better in the footer widget, for example, if you don’t want to change the template, or 100 more options):

Thank you! Our manager will contact you soon. Close a window

If you add the script not to the script file, but to the footer or js code editor, then wrap it in this code:

JQuery(document).ready(function($) ( // code ... ));

DOM events

By monitoring DOM events, you can do something at the right time while working with the form. For example, after a successful form submission, say “Thank you” in a pop-up window or redirect the user to another page.

List of form events

Wpcf7invalid Fired when a form was successfully submitted to the server, but mail was not sent because there were fields with invalid input. wpcf7spam Fired when a form was successfully submitted to the server, but no mail was sent because possible spam activity was detected. wpcf7mailsent Fires when the form has been successfully submitted to the server and mail has been sent to the recipient. wpcf7mailfailed Fired when the form was successfully submitted to the server, but the mail failed to be sent. This may be due to the fact that the hosting mail server does not work. wpcf7submit Fires when the form has been successfully submitted to the server, regardless of other incidents. Clicked the "Send" button - this action worked. wpcf7beforesubmit Fires before the wpcf7submit event, which allows any manipulation with formData - form data that will be sent to the server. Event added in CF7 v4.9.

The code from the examples below should be used where 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 to the wpcf7submit event of a container with the wpcf7 class and simply issues a warning when it occurs, that is, when you click on the “Submit” button, it immediately causes the message “Oops, they’re trying to send me... to Magadan!” Please note that an element with the wpcf7 class is a DIV with a form inside; the plugin generates all this independently. If you have several forms on the page, the code will only work for the first form found. Of course, you will replace the unnecessary alert() with a more useful action, for example, a beautiful form submission animation.

// We are looking for a block with a form that has the class wpcf7 (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("Guys, they're trying to send me... to Magadan!"); // Or something more useful), false) ;

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

// We look for a unique block with a form by its ID var wpcf7Elm = document.querySelector("#wpcf7-f92-p95-o1"); // Here we monitor the wpcf7submit event, 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 (or others) event for all, then we attach the event not to a separate block, but to the entire document:

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

How to track data entered 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 in the browser console, the data structure will be displayed:

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 go through each field and react to a specific 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 a field for (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 the handler.

Detail.contactFormId 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 shortcode itself. detail.pluginVersion Contact Form 7 plugin version. detail.contactFormLocale Form language code. For example, ru_RU. detail.unitTag Unit tag of the contact form. Each form has its own, for example wpcf7-f92-p95-o1. detail.containerPostId ID of the post whose content contains the form.

You can view all the data like this:

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

How to process a specific shape

For example, if you want to do something only 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);

Fight spam with Akismet

How to combat spam in the Contact Form 7 plugin? There are several mechanisms available, but only a couple are popular: reCAPTCHA and Akismet.

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

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

When you click the button, you will be redirected 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 website using a wordpress.com account
  • Select a tariff plan (there is a free one)
  • Adding a site to the service admin panel by clicking the "Activate this site" button

It's 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 a field, when generating it, you need to specify what rule to check by, for example:

Akismet:author Add this parameter to the username field.
Example: akismet:author_email Add this parameter to the field for entering the user's email.
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 require this check. Based on the collected data, Akismet will decide whether it is spam or not, so its completeness is important.

Contact Form 7 has several types of notifications:

Green frame for the notification The message was sent successfully Yellow frame for the notification Some fields were filled in with an error, the field did not pass validation Orange frame for the notification The message is marked as spam Red frame for the message Sending message failed

Now you can test the form with Akismet protection by entering “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 tab with Contact Form 7 forms is available to all users with the contributor role and higher. Only editors and administrators can edit forms. How to 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 administrators and super administrators have the manage_options right. Therefore, this 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 ability to edit forms. This setting must be stricter than or equal to WPCF7_ADMIN_READ_CAPABILITY. This is explained by the fact that you cannot edit forms without access to the admin panel.
Default: publish_pages

To better understand 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, "wpc f7_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)); if (isset ($meta_caps[$cap])) ( $caps = $meta_caps[$cap]; ) return $caps; )

From the code you can see that the capabilities array 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 Array constants ( => 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 method saves us from editing the wp-config.php file, but we will 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 opportunity values ​​$replace_caps = array("wpcf7_edit_contact_form" => "manage_options", "wpcf7_edit_contact_forms" => "manage_options", "wpcf7_read_contact_forms" => "manage_options", "wpcf7_del ete_contact_form" => " manage_options",); return array_replace($meta_caps, $replace_caps); )

Design of checkboxes and radio buttons

Contact Form 7 by default arranges checkboxes and radio buttons in a line. But this can be changed using tag settings for 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 is reversed:

To arrange checkboxes in a column, add a style line to the theme's CSS file:

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

To arrange checkboxes as a table, add a style line to the theme’s CSS file (additionally, the label_first parameter was used):

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

Load 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 differently, but it can be “prompted”.

Example 1 - completely disabling JavaScript and CSS and enabling where necessary Step 1 - disabling JavaScript and CSS on all pages of the site

There is a constant WPCF7_LOAD_JS 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 loading of plugin scripts.

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

Define("WPCF7_LOAD_CSS", false);

From plugin version 3.9 and higher, 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 spoiled. We need a mechanism to 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 the plugin developer's recommendation.

Example 2 - disabling scripts and styles wherever NOT needed

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

Option 1: ## Disable styles and plugin scripts everywhere except 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 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 - Enable scripts only when using form shortcode

First, we unconnect JS and CSS, and then we connect back only when the form shortcode is triggered. Thus, the files will be connected 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_init", "wpcf7_remove_assets"); function wpcf7_add_assets($atts) ( wpcf7_enqueue_styles(); return $atts; ) add_filter("shortcode_atts_wpcf7", "wpcf7_add_assets");

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

Form Tracking with Google Analytics

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

First, make sure you have the Google Analytics code, it looks something like this:

(function(i,s,o,g,r,a,m)(i["GoogleAnalyticsObject"]=r;i[r]=i[r]||function())( (i[r].q= i[r].q||).push(arguments)),i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o);a. async=1;a.src=g;m.parentNode.insertBefore(a,m) )(window,document,"script","//www.google-analytics.com/analytics.js","ga" ); ga("create", "UA-XXXXX-Y", "auto"); ga("send", "pageview");

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

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

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

document.addEventListener("wpcf7mailsent", function(event) ( ga("send", "event", "Contact Form", "submit"); ), false);

And this way 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, when the form is successfully submitted, you will see this event in the Google Analytics admin panel (Behavior -> Events -> Overview). It is possible that 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: an SEO specialist, a sales person and technical support. How can I use one form to send information to one of them personally? 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 - inserting a tag into the “To” field, which, when sending a letter, will take the user-selected mail from our drop-down list and insert it into the field.

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

[email protected] [email protected] [email protected]

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 modernize our tag like this:

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

SEO Specialist Sales TechSupport

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

Let's complicate the task even more...

Let’s imagine a situation where you need to send a letter to a selected recipient, for example, a SEO, and also a copy of the letter to the site manager for control.

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

So, the first copy comes to the 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 may not remember all the postal addresses of the specialists. Is there a need for a letter template to use not only the field value (in our case, the email address), but also the item title (the 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. Let's summarize the use of tags:

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

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 letter template settings tab has a field for sending additional headers (Additional Headers) according to the title-header: value rule. Each heading must start on a new line.

Let's consider the most popular ones - Reply-To, Cc and Bcc, read about the rest on Wikipedia.

Reply-To The name and address to which replies to this letter should be addressed. For example, you asked the user to indicate his email in a form. Use it so that the email client immediately knows to which email the response should be sent. Cc (from the English carbon copy) contains the names and addresses of the secondary recipients of the letter to whom the copy is sent. Bcc (from English blind carbon copy) contains the names and addresses of letter recipients 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 you use in the admin area. Change the language in Settings -> General -> Site language (drop-down list). But this will change the language for the entire site. What to do when your authors speak different languages?

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

Special message tags

Contact Form 7 supports several specific tags that may be needed when working with a form. For example, in the letter indicate the sender’s IP and the link to the page where the form was filled out. Special tags can be used in the email template or other form fields.

Sending 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 browser name, but also the operating system version and other parameters. [_url] This tag will be replaced with the address of the page from which the form was submitted. [_date] Will be replaced with the date the form was submitted. [_time] Will be replaced with the time the form was 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 serial number of the saved message. The Flamingo 1.5+ plugin must be installed, it is described below. Post tags

These tags will only work in the post content. If the form in the 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 ID of the post in whose content 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 currently registered user.

[_user_*] tags only work when Sender has an account and is logged in. If an unauthorized user submits the form, these tags will return an empty result and will have no meaning. It is recommended to enable the " " mode so that the form is displayed only for registered users.

If you need 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 the WP REST API and the specified tag will be skipped (replaced with an empty string).

[_user_login] Will be replaced with the user login. [_user_email] Will be replaced with the user's email. [_user_url] Will be replaced with the user's site URL. [_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 using Flamingo // You can do the same using the filter add_action("wpcf7_autop_or_not", "__return_false"); WPCF7_USE_PIPE When the value of the constant is false (true by default), Contact Form 7 begins to accept | like a regular symbol. WPCF7_ADMIN_READ_CAPABILITY Minimum role or ability to access the admin panel.
Default: edit_posts. WPCF7_ADMIN_READ_WRITE_CAPABILITY Minimum role or ability to edit forms. The default is publish_pages . This setting must be stricter than or equal to 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 link for temporary CAPTCHA files. WPCF7_UPLOADS_TMP_DIR Defining this constant will override the temporary folder path for uploaded files. WPCF7_VERIFY_NONCE

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

Add_filter("wpcf7_verify_nonce", "__return_true");

Redirect to another address after submitting the form

When you need to redirect the user to some page after successfully submitting a form, for example, with gratitude or a gift, use a JavaScript hook:

document.addEventListener("wpcf7mailsent", function(event) ( location = "http://example.com/"; ), false);

See DOM Events to understand how this works.

WordPress Spam Blacklist for Form Filtering

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

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

If a message sent through Contact Form 7 contains any of these words in its body, author name, URL, email or IP address, it will be marked as spam and will not be sent. Each word or IP is on a new line. A substring search is used, that is, using the word “buy”, “buy” will be found.

How can I find out the IP address from which spam is coming via Contact Form 7? The easiest way is to use the special [_remote_ip] tag. This tag is inserted into the letter template and will be replaced with the sender's IP address when sending the letter.

Contact Form 7 form design

I often provide the html code for one or another field in Contact Form 7. You can see which classes the plugin adds to fields by default. Now we’ll take a quick look at how to assign your own classes to form fields.

Which CSS should I 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 . Changing this file is a bad idea, because when you update the plugin, the file will be replaced and you will lose all changes. The same applies to public themes, which are also updated like plugins.

Therefore, to change styles, you need to select a style file that will not be updated. This could be a child theme's stylesheet. Or 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 (override) the Contact Form 7 styles in the theme styles.

Field styles in Contact Form 7

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

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

We often use more than one field in a form, so let’s assign 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 selector.wpcf7. 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 access this field:

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

Form style

We talked about field styles, but how to add design to the form itself? Let's use the wpcf7 class we already know, which is added to all forms of the plugin:

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

Customizing Error Messages

When submitting a form, if a required field is not filled out or is not validated, Contact Form 7 will display an error message. These messages can be customized.

Changing text

The text of a particular error or notification can be changed. For example, if you submit a form with a required field left blank, the message "Field is required." To change the text of this message, open the form editing, tab "Notifications when submitting the form". 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’s better to see once than to hear a hundred times, so watch:

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 field in a tooltip style. The tooltip disappears when you hover over it or when you focus on the field to which the tooltip belongs.

Floating style for desired field

To give 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

To avoid wrapping each field in a block with the use-floating-validation-tip class, we can “ask” the plugin to do this for us by specifying the html_class attribute with the value use-floating-validation-tip in the form shortcode:

If non-Ajax sending is used (with page reload), then regardless of the settings, a static error display style will be used.

Long Sheet Manager with Listo

Let's say we need to make a contact form where the user is asked 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 torture.

For example:

Managing such a “sausage” is difficult and the likelihood of making a mistake is high.

To solve this absurdity, there is a plugin Listo, which 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 can work with Listo (or vice versa, no one knows), which in turn works with fields: drop-down list, checkboxes and radio buttons. Thanks to this combination, you won’t have to painfully edit long lists, but you will be able to use short, predefined parameters.

How to manage long list options

For example, we decided to display a list of countries; for this we need a drop-down list 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” listing countries - Listo did it for us.

Additional settings

Each form can be specified additionally. parameters in the "Advanced settings" tab. Let's look at all these settings:

"Subscribers Only" mode

Subscribers_only: true

This mode (available from CF7 v7 4.9) allows you to display the form only for registered users. Unregistered users will see the message "This form is only available to registered users." 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 you use this code, the form will go into demo mode. In this mode, the contact form will skip the mail sending process and simply display "completed successfully" as the response message.

Skip email

Skip_mail: on

The skip_mail option 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.

Force 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 indicating what gender they are, but the user did not select anything, the plugin will generate 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 a message individually for this checkbox.

Preventing messages from being saved

Do_not_store: true

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

Executing JavaScript Code

This functionality comes in handy when you need to track user behavior. You can attach tracking to these hooks via Google Analytics or other statistics systems (discussed above).

on_sent_ok: "alert("sent ok");" on_submit: "alert("submit");" on_sent_ok the passed JavaScript will be executed after the form is successfully submitted. on_submit the passed JavaScript will be executed when the "Submit" button is clicked. Hiding Contact Form 7 after successfully submitting a message

We have a configured and working form. And it is necessary that when the user clicks on the “Send” button and the letter is sent to us, the form disappears, and in its place the text “Sent!” appears.

This is done simply: to do 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 that needs to be hidden. Instead of #contactform, you can specify another selector for the HTML element (form) that you want to hide.

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

Method 1 using JavaScript

This method was found on codepen.io and slightly reworked. The essence of the method is that JavaScript “reads the structure of the select tag and converts it to the desired format. The example will consider the field for selecting an engine:

Form template:

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

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 theme's js file or create a new js and include . Since the tag name was engines, in this code we indicate exactly that, that is, select .

Original html code of the select field

optgroup-Free Wordpress Joomla engines! Drupal Grav endoptgroup optgroup-Paid engines 1C-Bitrix DLE (DataLife Engine) UMI.CMS NetCat ImageCMS Shop endoptgroup

Processed html code of the select field

Wordpress Joomla! Drupal Grav 1C-Bitrix DLE (DataLife Engine) UMI.CMS NetCat ImageCMS Shop

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

Contact Form 7 can manage multiple contact forms where you can flexibly customize form and mail content with fairly simple layout. Forms have built-in support for Ajax submission, CAPTCHA, Akismet spam filter and more.

Documentation and support Screenshots Installation
  • Upload the entire contact-form-7 folder to the /wp-content/plugins/ directory.
  • Activate the plugin from the Plugins page in your WordPress dashboard.
  • In the WordPress console menu, you will find the ‘Feedback’ tab.

    To learn how to use the plugin correctly, you can visit its home page.

    Participants and developers

    Contact Form 7 is an open source project. The following contributors contributed to the development of the plugin:

    Participants Change Log

    For more information, see Releases.

    5.1.4
    • reCAPTCHA: Introducing the WPCF7_RECAPTCHA_SITEKEY and WPCF7_RECAPTCHA_SECRET constants.
    • reCAPTCHA: Introducing the wpcf7_recaptcha_sitekey and wpcf7_recaptcha_secret filter hooks.
    • Adding $status parameter to wpcf7_form_response_output filter.
    • Generates a random code when the user is a registered user.
    • Introducing WPCF7_ContactForm::unit_tag(), a public method that returns a unit tag.
    • reCAPTCHA: issues a different message in the spam log in cases where the response token is empty.
    • Consent flag: Support label_first option in form consent tag.
    5.1.3
    • Fixed a bug that resulted in the inability to deselect an option in the Mail tab.
    5.1.2
    • Constant Contact: Introduced contact list selector.
    • Constant Contact: An additional setting, constant_contact, is introduced.
    • reCAPTCHA: Introduced wpcf7_recaptcha_actions and wpcf7_recaptcha_threshold filter hooks.
    5.1.1
    • reCAPTCHA: Changes the response to empty response tokens.
    5.1
    • The integration module Constant Contact has been introduced.
    • The reCAPTCHA module has been updated to support reCAPTCHA v3.
    • Adds Dark Mode style rules.
    5.0.5
    • Fixed inconsistency issue between get_data_option() and get_default_option() in WPCF7_FormTag class.
    • Suppresses PHP errors that occur when calling unlink().
    • Introduced wpcf7_is_file_path_in_content_dir() to support the UPLOADS constant.
    5.0.4
    • Explicitly sets the power_type argument in the register_post_type() call to fix an issue with unauthorized privilege escalation.
    • Local file attachment - it is prohibited to specify absolute paths to files located outside the wp-content directory.
    • Configuration Validator - Adds a test element to detect incorrect attachment file settings.
    • Fixed a bug in the JavaScript backwards compatibility feature for legacy browsers that do not support the HTML5 placeholder attribute.
    • Consent checkbox - disables the do-not-store function of the form tag.
    5.0.3
    • CSS: Applying "not allowed" cursor style when hovering over submit buttons in inactive state.
    • Consent flag: Overhaul of the tag generator user interface to encourage the use of better privacy options.
    • Implementation of wpcf7_anonymize_ip_addr() function.
    • Introduced consent_for:storage option for all form tag types.
    5.0.2
    • Added a "Privacy Notices" section to the readme.txt file.
    • Updated content in the Information meta block.
    • Use get_user_locale() instead of get_locale() where more appropriate.
    • Consent flag: Resets the disabled status of submit buttons after successful application.
    5.0.1
    • Fixed incorrect use of _n().
    • Configuration Check: Fixed incorrect number of warnings on the Advanced Options tab.
    • Configuration check: Fixed incorrect handling of the [_site_admin_email] special email tag in the From header field.
    • Acceptance checkbox: The specified class and id attributes were applied to the wrong HTML element.
    • Configuration check: If there is an optional mail header for mailboxes such as Cc or Reply-To, but a possible empty value, an "Invalid mailbox syntax" error will be returned.
    • Explicitly specify the fourth parameter to add_action() to avoid passing unintended parameter values.
    • Check if the target directory is empty before deleting it.
    5.0
    • Additional settings: on_sent_ok and on_submit have been removed.
    • New additional setting: skip_mail.
    • Flamingo: The title of the incoming channel changes along with the title of the corresponding contact form.
    • DOM events. The entire API response object is accessible through the event.detail.apiResponse property.
    • HTML Mail: Adds language-related attributes to the HTML header.
    • File Upload: Sets the accept attribute in the upload field.
    • A new class WPCF7_MailTag has been introduced.
    • Allows you to abort an attempt to send mail using the wpcf7_before_send_mail action hook. Additionally, you can set a custom status and message via an action interceptor.
    • Acceptance checkbox: Allows you to specify conditions within the content portion of the form tag.
    • Acceptance checkbox: Supports the optionality parameter.
    • New special mail tags: [_site_title], [_site_description], [_site_url], [_site_admin_email], [_invalid_fields], [_user_login], [_user_email], [_user_url], [_user_first_name], [_user_last_name], [_user_nickname], and [_user_display_name].
    • New filter hooks: wpcf7_upload_file_name, wpcf7_autop_or_not, wpcf7_posted_data_($type), and wpcf7_mail_tag_replaced_($type)
    • New form-tag features: zero-controls-container and not-for-mail

    A feedback form is present on every website; it is something like an integral part of the web resource. Since it serves as an appeal to the administrator with any proposal or claim in the area of ​​their interests. And such cases happen often, especially if you are a company, organization, or just a private enterprise that produces some kind of product.

    To create a feedback form on WordPress, you don’t have to write the code yourself or have a specialist write it. This has already been implemented and even repeatedly, all you need to do is select a plugin that meets your requirements. The article discusses 5 more popular plugins that are in demand at the proper level.

    One of the most widely used plugins for creating contact forms is Contact form 7. It quickly gained popularity due to its ease of customizing the form content. Plus supports spam filtering and allows you to set CAPTCHA using the additional Really Simple CAPTCHA plugin. The plugin also supports Ajax technology, which means that the web page does not reload while processing the request.

    After installing and activating Contact form 7, a new tab for managing forms will appear in the control panel. To find a common language with it, you won’t have to tinker for a long time; the plugin is multilingual and Russian is also available. The contact form is styled depending on the theme you have installed, but with knowledge of CSS it is possible to edit it to your liking.

    Example form.

    2.Form Maker

    Form Maker is a modern and advanced tool for quickly creating contact forms. It offers many field types, captcha installation, ready-made form templates, open source code for editing styles, and the result can be immediately seen in the preview. If you purchase the commercial version, integration with Google Maps will be available, as well as a file upload field. The plugin supports a large number of languages.

    Example form.

    3. Fast Secure Contact Form

    A simple and at the same time powerful feedback form has a number of positive functions and settings. You won't have to worry about being flooded with spam because the plugin supports Akismet and allows you to set CAPTCHA. It is also possible to export and import settings, redirect the user after sending an email to any address, send files, edit styles and much more. Partial Russian translation.

    Example form.

    4. Visual Form Builder

    A very convenient and simple feedback form. All settings and functions are available on one page, which makes it easy to manage. It has many fields that can be easily added with one click of the mouse. There is also the possibility of redirecting after sending a letter, anti-spam, form adaptability and much more.

    Settings window.

    Example form.

    5. Slick contact forms

    A very simple form, it doesn’t have a ton of settings, huge functionality, only 4 fields and nothing superfluous. The plugin differs from others in that the form is displayed through a widget and creates the effect of a floating or sliding form on the page. When pressed, it smoothly appears from the side, from above, etc. depends on the settings you choose.

    Example form.