简体   繁体   English

如何通过联系表7获取最后插入的ID,然后将其分配给全局变量

[英]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. 我正在尝试通过联系表格7获取最后插入的id值,然后将其分配给全局变量以在另一个PHP文件的函数中使用它。

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: 现在进行测试,我创建此函数以回显最后插入的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. 我不知道为什么,但是它一直返回到0。已经一个月了,我无法解决这个问题。 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. 据我所知,CF7没有将表单提交到任何数据库表中。 So you cant get the last inserted ID, because it doesn't exists. 因此您无法获取最后插入的ID,因为它不存在。

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/ 您可以通过使用CF7操作(例如“ wpcf7_before_send_mail”)保存数据,获取数据并将其插入到某些自定义表中,也可以使用插件-> https://wordpress.org/plugins/flamingo/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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