首页 > 解决方案 > 如何在重定向页面上访问联系表格 7 提交的数据?

问题描述

我正在使用联系表 7 进行调查。当我单击联系表格 7 提交按钮时,它会重定向到感谢页面。我想把我提交的所有数据都提交到感谢页面。我该怎么做 ?

标签: wordpressformsredirectcontact-form-7

解决方案


有两种方法可以实现这一点,

1.使用存储提交数据的插件,例如Post My CF7 Form(插件页面上有一个常见问题解答,说明如何访问重定向页面上存储的提交)。

2.如果您不想存储和保留提交的数据,那么您需要将提交的数据保存到瞬态并从重定向页面访问它,您可以这样做,

第 1 步:使用 WP nonce作为表单中的隐藏字段识别当前提交(即使对于未登录的用户也有效) ,并放置一个 js 脚本以在触发成功提交事件后重定向到您的页面使用挂在 cf7显示过滤器上的匿名函数do_shortcode_tag

add_filter('wpcf7_form_hidden_fields','add_hidden_nonce');
function add_hidden_nonce($fields){
  $nonce = wp_create_nonce('cf7-redirect-id');
  $fields['redirect_nonce'] = $nonce;
  /*
   hook the shortcode tag filter using an anonymous function 
   in order to use the same nonce and place a redirect js event 
   script at the end of the form. 
  */
  add_filter('do_shortcode_tag', function($output, $tag, $attrs) use ($nonce){
    //check this is your form, assuming form id = 1, replace it with your id.
    if($tag != "contact-form-7" || $attrs['id']!= 1) return $output;
    $script = '<script>'.PHP_EOL;
    $script .= 'document.addEventListener( "wpcf7mailsent", function( event ){'.PHP_EOL;
    //add your redirect page url with the nonce as an attribute.
    $script .= '    location = "http://example.com/submitted/?cf7="'.$nonce.';'.PHP_EOL;
    $script .= '  }'.PHP_EOL;
    $script .= '</script>'.PHP_EOL;
    return $output.PHP_EOL.$script;
  },10,3);
  return $fields;
}

第 2 步:一旦提交通过验证/并发送电子邮件,就挂钩 cf7 操作“wpcf7_mail_sent”。

add_action('wpcf7_mail_sent', 'save_posted_data_into_transient');
function save_posted_data_into_transient(){
  if(isset($_POST['redirect_nonce'])){ //save the data.
    //save the posted data from the form.  Note if you have submitted file fields you will also need to store the $_FILES array.
    set_transient('_cf7_data_'.$_POST['redirect_nonce'], $_POST, 5*60); //5 min expiration.
  }
}

第 3 步:在您的重定向页面上,您现在可以访问存储的瞬态数据,将其放在页面模板的顶部,

<?php
if( isset($_GET['cf7']) ){
  $transient = '_cf7_data_'.$_GET['cf7'];
  $data = get_transient($transient);
  //$data['my-text-field']....
}
?>

推荐阅读