Home > Net >  Update user meta after cf7 submit WP
Update user meta after cf7 submit WP

Time:05-21

I want to substract 1 from user meta after cf7 form submittion. I've got this function but it doesn't work:

$user_id = get_current_user_id();
add_action( 'wpcf7_before_send_mail', 'process_contact_form_data' );
function process_contact_form_data( $contact_data ){

   $user_last = get_user_meta( $user_id, 'QuestionAvailiable', true ); 
    $user_last_sum =  $user_last - 1;
    update_user_meta( $user_id, 'QuestionAvailiable', $user_last_sum);          
}

QuestionAvailiable is still 3 after form submit, not 2. What's wrong?

CodePudding user response:

The current user id is passed through the form by hidden meta fields which are accessible via the method get_meta(field)

This should work for you.

add_action( 'wpcf7_before_send_mail', 'process_contact_form_data' );
function process_contact_form_data( $contact_data ) {
    $user_last     = get_user_meta( $contact_data->get_meta( 'current_user_id' ), 'QuestionAvailiable', true );
    $user_last_sum = absint( $user_last ) - 1;
    update_user_meta( $contact_data->get_meta( 'current_user_id' ), 'QuestionAvailiable', $user_last_sum );
}

For reference, the following are the meta fields that are available to the $contact_form object which is the first parameter of the wpcf7_before_send_mail hook.

array(
    'timestamp'         => integer,
    'remote_ip'         => string,
    'remote_port'       => integer,
    'user_agent'        => string,
    'url'               => 'current_url',
    'unit_tag'          => string,
    'container_post_id' => integer,
    'current_user_id'   => integer,
    'do_not_store'      => bool,
);
  • Related