In WordPress, if you are using the Contact Form 7 plugin and you want to add a function before submitting the form, you can use the wpcf7_before_send_mail
hook. This hook allows you to execute custom code just before the form is submitted.
Here’s an example of how you can use this hook to perform an action before sending the email:
- Open your theme’s
functions.php
file (you can find this file in your theme’s directory). - Add the following code:
// functions.php
function custom_before_send_mail($contact_form) {
// Get the posted data from the form
$posted_data = $contact_form->posted_data;
// Perform your custom action based on the form data
$message = $posted_data['your-message'];
// Example: Check if the message contains a specific word
if (stripos($message, 'restricted-word') !== false) {
// Prevent the form from being sent
$contact_form->skip_mail = true;
// Display a message to the user
$contact_form->response_output = 'Sorry, the form cannot contain the restricted word.';
}
}
add_action('wpcf7_before_send_mail', 'custom_before_send_mail');
Make sure to replace 'your-message'
it with the actual name of the textarea or input field in your Contact Form 7 form.
This example checks if a specific word ('restricted-word'
) is present in the form’s message field. If the word is found, it prevents the form from being sent and displays a custom message.
Adjust the code according to your specific needs and the structure of your Contact Form 7 form.