You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:PHP钩子wpcf7_mail_sent与JS事件wpcf7mailsent协同问题及表单功能实现

Hey there, let's break down how to fix both your form submission issues and get the PHP hook + JS event working together smoothly. I've dealt with similar Contact Form 7 headaches before, so here's a step-by-step solution that should do the trick:

1. Fixing Database Insertion with wpcf7_mail_sent

The wpcf7_mail_sent hook fires right after the form sends an email, making it the perfect spot to save submissions to your database. The most common issues here are missing sanitization, incorrect form targeting, or unhandled errors breaking the workflow. Here's a robust implementation:

add_action('wpcf7_mail_sent', 'cf7_save_submission_to_db');
function cf7_save_submission_to_db($contact_form) {
    // Target only your specific form (replace 123 with your form's actual ID)
    $target_form_id = 123;
    if ($contact_form->id() !== $target_form_id) return;

    // Get the submission data safely
    $submission = WPCF7_Submission::get_instance();
    if (!$submission) return;

    $posted_data = $submission->get_posted_data();

    // Sanitize each field (match the names to your CF7 form fields)
    $name = sanitize_text_field($posted_data['your-name'] ?? '');
    $email = sanitize_email($posted_data['your-email'] ?? '');
    $message = sanitize_textarea_field($posted_data['your-message'] ?? '');

    global $wpdb;
    $table_name = $wpdb->prefix . 'contact_form_submissions'; // Custom table name

    // Insert data with prepared statements to prevent SQL injection
    $result = $wpdb->insert(
        $table_name,
        array(
            'name' => $name,
            'email' => $email,
            'message' => $message,
            'submitted_at' => current_time('mysql')
        ),
        array('%s', '%s', '%s', '%s') // Define data types
    );

    // Optional: Log errors for debugging
    if ($wpdb->last_error) {
        error_log('CF7 DB Insert Error: ' . $wpdb->last_error);
    }
}

Important Pre-Requisite:

First, create your custom database table (run this once, then remove it from your functions.php):

function cf7_create_submission_table() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'contact_form_submissions';
    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE $table_name (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        name varchar(255) NOT NULL,
        email varchar(255) NOT NULL,
        message text NOT NULL,
        submitted_at datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
        PRIMARY KEY  (id)
    ) $charset_collate;";

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}
add_action('init', 'cf7_create_submission_table');
2. Implementing Post-Submission Redirect with wpcf7mailsent

The wpcf7mailsent JS event only fires if the entire CF7 workflow completes successfully (including your PHP hook). Here's a reliable way to bind the redirect:

document.addEventListener('DOMContentLoaded', function() {
    document.addEventListener('wpcf7mailsent', function(event) {
        // Replace with your thank-you page URL
        window.location.href = '/thank-you/';
    }, false);
});

jQuery (If Your Theme Loads jQuery):

jQuery(document).ready(function($) {
    $(document).on('wpcf7mailsent', function(event) {
        window.location.href = '/thank-you/';
    });
});
3. Fixing wpcf7_mail_sent and wpcf7mailsent Synergy

The most common reason these two don't play nice is that your PHP hook is breaking the CF7 workflow. Here's how to fix it:

  • Never use die() or exit() in your wpcf7_mail_sent function—this stops CF7 from triggering the JS event.
  • Add error handling: Wrap critical code in try/catch blocks to prevent fatal errors from stopping execution.
  • Validate CF7 email settings: If the form fails to send an email, wpcf7_mail_sent won't fire at all. Double-check your "Mail" tab settings in CF7.
  • Debug with logs: Add error_log('Entered CF7 DB hook'); at the start of your PHP function to confirm it's being triggered.
Quick Debug Checklist
  1. Confirm your form ID in the PHP hook matches the ID in your CF7 shortcode (e.g., [contact-form-7 id="123" ...])
  2. Check your browser console (F12 > Console) for JS errors
  3. Enable WP_DEBUG_LOG in wp-config.php to catch PHP errors
  4. Test the redirect first without the database code to isolate issues

内容的提问来源于stack exchange,提问作者John Lev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:09:31