【发布时间】:2021-11-21 01:29:56
【问题描述】:
我正在尝试将我的页面重定向到我从 curl 发布响应中获得的 url。
这是我的代码:
add_action( 'wpcf7_mail_sent', 'action_wpcf7_mail_sent');
function action_wpcf7_mail_sent( $contact_form ) {
if ( $contact_form->id !== 127 )
return;
$wpcf7 = WPCF7_ContactForm::get_current();
$submission = WPCF7_Submission::get_instance();
$save = $submission->get_posted_data();
$data = //the data I send
$url= 'http://my-url';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: application/json']);
$response = json_decode(curl_exec($ch));
curl_close ($ch);
//I need to redirect my contact form to response['redirect_url']
};
我需要将我的联系表单重定向到响应['redirect_url']
我尝试了多种方法,但都不起作用:wp_redirect($response["redirect_url"]);
header( 'Location: '.$response["redirect_url"] );
两者都使用exit; 和
?><script type="text/javascript">
location = <?php echo $response["redirect_url"] ?>;
</script><?php
但是他们都给出了错误。
如果您有任何想法,请告诉我!
编辑
我试着稍微改变一下我的代码!
我试图从 js 中捕获 cf7mailsent,然后像这样调用 php 函数:
document.addEventListener( 'wpcf7mailsent', function( event ) {
var inputs = event.detail.inputs;
$.ajax({
type: "POST",
datatype:"json",
url:jsforwp_globals_sub.ajax_url,
data: {
action:"send_this_data",
ajax_nonce:jsforwp_globals.send_info,
info:inputs,
}
}).done(function(mess) {
msg=jQuery.parseJSON(mess);
if(typeof msg['redirect_url']!="undefined"){
window.location.href = msg['redirect_url'];
}else if(typeof msg['message']!="undefined"){
alert(msg['message']);
}else{
alert('failed'+mess);
}
}).fail(function(xhr, status, error) {
});
});
add_action("wp_ajax_nopriv_send_this_account","action_wpcf7_mail_sent");
function action_wpcf7_mail_sent() {
$save=$_POST["inputs"];
//the rest of the code from $save = $submission->get_posted_data();
echo json_encode($response);
wp_die();
}
但它不起作用,什么是正确的解决方案?
非常感谢!
更多信息
问题是当我尝试使用 $save 时,我很确定它会给出 null
【问题讨论】:
-
这是否为您提供了更好的方法? - contactform7.com/redirecting-to-another-url-after-submissions
-
不幸的是,我从functions.php中检索了需要将用户重定向到的url,所以我不知道如何在那里传递url
-
两件事。 1:你应该使用这个与你正在做的
$contact_form->id()来获取表单的ID。 2. 您需要将 ajax 操作附加到wpcf7mailsentDOM 对象以获取 URL。要么禁用 JS 提交,要么不使用 ajax/wp-json API 表单提交。 -
谢谢!我一直在尝试。我在将联系表单的值传递给 php 函数时遇到问题,有什么线索吗?我将更改问题以显示新代码。
-
您的操作需要
send_this_data,但您的wp_ajax_nopriv_send_this_account使用send_this_account- 我还会为登录用户添加wp_ajax_{action}。
标签: wordpress redirect contact-form-7