How to get current post ID in Contact Form 7 wpcf7_before_send_mail hook action

I’m trying to handle the CF7 data before send and update the current post custom field using ACF function but I’m unable to get the current post ID the form is send from. I’ve also tried getting the ID from global $post variable and get_queried_object_id() but it didn’t work either.

Any idea how can I get the ID of the post the form was send from?

function dv_wpcf7_handle_form_data($wpcf7)
{
    $submission = WPCF7_Submission::get_instance();

    if ($submission) {
        $posted_data = $submission->get_posted_data();
    }

    // Check for ID of specific WPCF7 form
    if ($wpcf7->id() == 128) {
        $number_order = $posted_data['customer-number'];
        $number_current_value = get_field('trip_available_seats', get_the_ID()); // passing the ID to function doesn't work
        $number_new_value = $number_current_value - $number_order;

        if ($number_new_value >= 0) {
            update_field('trip_available_seats', $number_new_value, get_the_ID());
        } else {
            $error = true;
            $err_msg = 'Error message...';
        }
    }

    if (isset($error) && $error === true) {
        $msgs = $wpcf7->prop('messages');
        $msgs['mail_sent_ok'] = $err_msg;
        $wpcf7->set_properties(array('messages' => $msgs));
        add_filter('wpcf7_skip_mail', 'abort_mail_sending');
    }

    return $wpcf7;
}
add_action('wpcf7_before_send_mail', 'dv_wpcf7_handle_form_data');

function abort_mail_sending($contact_form)
{
    return true;
}

4 s
4

Due to a backwards-incompatible change in version 5.2, you can no longer retrieve the form’s meta data using get_posted_data().

Instead, you can use the id value in the array returned by get_current():

$contact_form = WPCF7_ContactForm::get_current();
$contact_form_id = $contact_form -> id;

Leave a Comment