我有一个联系表格7,是发送信息到一个API。我想在前端显示API响应。
我记录用户信息,然后使用wp_remote_post发布它,并使用我的示例url。我希望能够在前端显示API响应/ $body。我已经将其设置为在调试日志中捕获它,但我想知道是否有一种方法可以将它发布到我的表单所在的前端。
正常的Var转储和print_r不工作,因为联系人表单7是Ajax函数。
add_action('wpcf7_mail_sent','Kiri_cf7_api_sender');
function Kiri_cf7_api_sender ( $contact_form) {
if ( $contact_form->title === 'Quote_form')
{
$submission = WPCF7_Submission::get_instance();
if ($submission)
{
$posted_data = $submission->get_posted_data();
$name = $posted_data["your-name"];
$surname = $posted_data["your-name2"];
$phone = $posted_data["tel-922"];
//example url//
$url = www.mytestapi.com?$name&$surname&$phone;
$response = wp_remote_post ($url);
$body = wp_remote_retrieve_body( $response );
ob_start(); // start buffer capture
var_dump($name);
var_dump($surname);
var_dump($phone);
$contents = ob_get_contents(); // put the buffer into a variable
ob_end_clean(); // end capture
error_log($contents);
}
}
}发布于 2021-09-24 12:47:28
我有一个联系表格7,是发送信息到一个API。我想在前端显示API响应。
解决这类问题有两种方法,
1-使用CF7插件的消息响应挂钩,
add_filter('wpcf7_display_message', 'my_response_msg',10,2);
function my_response_msg($message, $status){
if('mail_sent_ok'==$status){
$form = wpcf7_get_current_contact_form(); //in case you need the cf7 form object to validate....
$message = 'Api response is: '. $api;
}
return $message;
}但是,请记住,您只能在此消息中使用文本,由于CF7插件报告的这里和这里的局限性,HTML将无法工作,正如您所了解的那样,功能确实存在,但是插件的作者倾向于在此类问题上埋头苦干。
2-如果您需要一个更丰富的接口,那么您可以将表单提交过程重定向到另一个页面,使用与此回答类似的逻辑将其存储在瞬态中,从而显示您的API响应.
或者,您可以在表单页面上加载自定义JavaScript,在CF7成功提交wpcf7mailsent 事件上触发该页面,然后使用AJAX请求获取存储在服务器上的临时API请求。
https://wordpress.stackexchange.com/questions/395980
复制相似问题