简体   繁体   中英

How to get last inserted id via Contact Form 7, and then assign it to a global variable

I'm trying to get last inserted id value via Contact Form 7, and then assign it to a global variable to use it in a function in another PHP file.

Here's my code:

$lastid = 0;

function user_data_form( $wpcf7 ) {

global $wpdb;

$wpcf7 = WPCF7_ContactForm::get_current();
$form = WPCF7_Submission::get_instance();

  if ($form) {
     $data = $form->get_posted_data();

     if ( $wpcf7->id == 5285 ) {

        $name = $data['name'];
        $email = $data['email'];
        $bio = $data['bio'];
        $url = $data['url'];            

        $wpdb->insert( $wpdb->prefix . 'user_data', 
        array( 
            'name'  => $name,
            'email' => $email,
            'bio' => $bio,
            'url' => $url
            ), array( '%s', '%s', '%s', '%s' )
        );
        $lastid = $wpdb->insert_id;
      }
   }
}
add_action( 'wpcf7_before_send_mail', 'user_data_form' );

After form submit successfully it will redirect to another page. Now to test it out, I create this function to echo the last inserted ID:

function echo_last_id() {
   global $wpdb;
   global $lastid;
      echo $lastid;
      var_dump($lastid);
}
add_shortcode( 'get-id', 'echo_last_id' );

I don't know why but it kept returning to 0. It's been a month that I unable to solve this. If someone can help me I would be forever grateful.

As far as I know CF7 is not submitting the forms into any database table. So you cant get the last inserted ID, because it doesn't exists.

You can save the data by using the CF7 actions like "wpcf7_before_send_mail", grabbing the data and inserting it to some custom table, or you can use plugin like -> https://wordpress.org/plugins/flamingo/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM