我沿着 Javascript 路线走下去,它可以工作......但是你无法访问提交的变量(至少我看不出你会怎么做)。在这里,我将我的 Javascript 代码移植到 PHP 代码中。
您可以访问表单中任何隐藏或显示的输入,并使用它们来构建 URL。
在 PHP 而不是 Javascript 中进行重定向需要一个技巧,那就是您必须按照 doc 关闭 CF7 Javascript。把它放在你的wp-config.php
:
define('WPCF7_LOAD_JS', false);
然后你可以把它放在你的主题中functions.php
:
add_action( 'wpcf7_mail_sent', 'icc97_so_mail_sent', 10, 3);
/**
* Ported Javascript code to redirect the CF7 form
*
* Have to do it in PHP because we want access to the POSTed data
*
* There is a further complication that the default CF7 submission is AJAX
* Then our WP redirect doesn't do anything
* So we have to turn off the CF7 Javascript via wp-config.php
*
*/
function icc97_so_mail_sent( $contact_form ) {
$submission = WPCF7_Submission::get_instance();
$data = $submission->get_posted_data();
// example data:
// {"_wpcf7":"11684","_wpcf7_version":"4.9","_wpcf7_locale":"en_GB","_wpcf7_unit_tag":"wpcf7-f11684-p11681-o1","_wpcf7_container_post":"11681","your-name":"Ian","your-organisation":"Stack Overflow","your-email":"ian@example.com","your-agreement":"1"}
/**
* Get an attribute value from the CF7 form
*
* @param string $name attribute name
* @return string attribute value
*/
$attr = function($name) use ($data) {
$val = $data[$name];
// Dropdown / select values are arrays could be a one element array
return is_array($val) ? $val[0] : $val;
};
/**
* Create URL for downloads page
*
* @param string $domain e.g. https://example.com, can be blank for relative
* @param array $names attributes
* @return string URL e.g. https://example.com/downloads/x/x/x/?data=xxx
*/
$buildUrl = function ($domain, $names) use ($attr) {
$stub = [$domain, 'downloads'];
// we want lower case, attributes
$path = array_map('strtolower', array_map($attr, $names));
// create an array of the full URL and then join with '/'
return join('/', array_merge($stub, $path));
};
$domain = '';
// this requires AJAX to be turned off - see function doc block
\wp_redirect($buildUrl($domain, ['your-name', 'your-organisation']));
// exit otherwise CF7 forces it's own redirect back to the original page
exit;
}