Contact Form with Recaptcha Plugin

This WordPress plugin provides a simple yet secure contact form with conditional visibility of fields and Google Recaptcha integration. It ensures user inputs are sanitized, and email notifications are sent upon successful form submissions.

<?php /** * Plugin Name: Contact Form with Conditional Visibility and Recaptcha * Description: A simple contact form with conditional visibility and Recaptcha protection. * Version: 1.0 * Author: CodeWP Assistant * Author URI: * Text Domain: codewp */ // Define constants for Recaptcha (v2) keys define('RECAPTCHA_SITE_KEY', 'YourRecaptchaSiteKey'); define('RECAPTCHA_SECRET_KEY', 'YourRecaptchaSecretKey'); add_action("rest_api_init", "cwpai_register_api_hooks"); function cwpai_register_api_hooks() { register_rest_route("cwpai/v1", "/submit-form/", ["methods" => "POST", "callback" => "cwpai_submit_form", "permission_callback" => "__return_true", ]); } function cwpai_submit_form(WP_REST_Request $request) { // Nonce verification $nonce = $request->get_header("X-WP-Nonce"); if (!wp_verify_nonce($nonce, "wp_rest")) { return new WP_Error("rest_forbidden", esc_html__("You do not have permissions to access this service.", "codewp"), ["status" => rest_authorization_required_code() ]); } // Sanitize input $name = sanitize_text_field($request["name"]); $contact_type = sanitize_text_field($request["contact_type"]); $contact_info = sanitize_text_field($request["contact_info"]); $message = sanitize_textarea_field($request["message"]); $recaptcha_response = sanitize_text_field($request->get_param("recaptcha")); // Recaptcha validation $recaptcha_verify = wp_remote_post("", ["body" => ["secret" => RECAPTCHA_SECRET_KEY, "response" => $recaptcha_response, ], ]); $recaptcha_data = wp_remote_retrieve_body($recaptcha_verify); if (is_wp_error($recaptcha_data) || empty($recaptcha_data)) { return new WP_Error("recaptcha_error", __("There was a problem verifying the Recaptcha, please try again.", "codewp"), ["status" => 400]); } $recaptcha_data = json_decode($recaptcha_data); if (!$recaptcha_data->success) { return new WP_Error("recaptcha_failed", __("Recaptcha verification failed, please try again.", "codewp"), ["status" => 401]); } // Send email $to = get_option("admin_email"); $subject = "New Contact Form Submission"; $body = "Name: {$name}\nContact Type: {$contact_type}\nContact Info: {$contact_info}\nMessage: {$message}"; wp_mail($to, $subject, $body); return new WP_REST_Response(["status" => "success", "message" => __("Your message has been successfully sent.", "codewp"), ], 200); } add_shortcode("cwpai_contact_form", "cwpai_contact_form_shortcode"); function cwpai_contact_form_shortcode() { wp_enqueue_script("jquery"); wp_enqueue_script("google-recaptcha", ""); // Localize script with nonce for REST API wp_localize_script("jquery", "cwpai_settings", ["root" => esc_url_raw(rest_url()), "nonce" => wp_create_nonce("wp_rest"), ]); ob_start(); ?> <form id="cwpai_contact_form"> <input type="text" name="name" placeholder="<?php _e("Name", "codewp"); ?>" required> <input type="radio" name="contact_type" value="phone" checked> <?php _e("Phone", "codewp"); ?> <input type="radio" name="contact_type" value="email"> <?php _e("Email", "codewp"); ?> <input type="text" name="contact_info" id="contact_info" placeholder="<?php _e("Phone number", "codewp"); ?>" required> <textarea name="message" placeholder="<?php _e("Your message", "codewp"); ?>" required></textarea> <div class="g-recaptcha" data-sitekey="<?php echo RECAPTCHA_SITE_KEY; ?>"></div> <button type="submit"><?php _e("Submit", "codewp"); ?></button> </form> <script type="text/javascript"> jQuery(document).ready(function ($) { $('#cwpai_contact_form').on('submit', function (e) { e.preventDefault(); var formData = new FormData(this); formData.set('name', $('#cwpai_contact_form input[name="name"]').val()); formData.set('contact_type', $('#cwpai_contact_form input[name="contact_type"]:checked').val()); formData.set('contact_info', $('#cwpai_contact_form input[name="contact_info"]').val()); formData.set('message', $('#cwpai_contact_form textarea[name="message"]').val()); formData.set('recaptcha', grecaptcha.getResponse()); $.ajax({ url: cwpai_settings.root + 'cwpai/v1/submit-form/', method: 'POST', data: formData, contentType: false, processData: false, beforeSend: function (xhr) { xhr.setRequestHeader('X-WP-Nonce', cwpai_settings.nonce); }, success: function (response) { alert(response.message); if (response.status === 'success') { $('#cwpai_contact_form')[0].reset(); grecaptcha.reset(); } }, error: function (response) { alert(response.responseJSON.message); } }); }); }); </script> <?php return ob_get_clean(); }

Frequently Asked Questions

The plugin adds a contact form to your WordPress site with conditional visibility for fields and Google Recaptcha integration for spam protection.