我想將表單中的一些欄位添加到產品的自定義欄位中,以便在付款后將它們用于 API 呼叫。我的表單上有一個重定向到結帳頁面并將產品添加到購物籃中,代碼如下:
<script>
document.addEventListener( 'wpcf7mailsent', function( event ) {
if (jQuery("input[type='checkbox'][name='try[]']").is(':checked')) {
location = 'http://www.thelittlegym.co.za/checkout/?add-to-cart=2506';
}
}, false );
</script>
然后,我的 function.php 中有一些代碼可以將表單資料保存在 WC 會話中。我必須添加宣告新會話,否則設定功能不起作用。如果我執行初始化,則會收到一條錯誤訊息“wc_empty_cart();” 未定義(此函式來自 WooCommerce 插件。
add_action('wpcf7_before_send_mail', 'send_form_data_to_wc_session', 5, 1);
function send_form_data_to_wc_session($contact_form) {
$submission = WPCF7_Submission::get_instance();
if($submission) {
$posted_data = $submission->get_posted_data();
if (!empty($posted_data['try'][0])) {
// Set data to WooCommerce session
WC()->session = new WC_Session_Handler();
// WC()->session->init();
WC()->session->set('cf7_posted_data', $posted_data);
}
}
}
最后,我嘗試使用下面的代碼檢索會話資料。var 轉儲只回傳 NULL。
add_action('woocommerce_checkout_before_customer_details', 'wc_save_cf7_data_to_order', 10, 1);
function wc_save_cf7_data_to_order($order_id) {
$posted_data = WC()->session->get('cf7_posted_data');
var_dump($posted_data);
if(!empty($posted_data)) {
foreach($posted_data as $key => $data) {
echo '<b>', $key, ' : </b> ', $data, '<br />';
}
WC()->session->__unset('cf7_posted_data');
}
}
我相信 WC 會話集不起作用。我在控制臺中查找會話存盤,只能看到“wc_cart_hash_xxxxxxx”、“wc_fragment_xxxxxxx”和“wc_cart_created”。
知道如何繼續除錯嗎?
uj5u.com熱心網友回復:
我找到了關于另一個主題的替代解決方案,即使它沒有解釋為什么上面的代碼不起作用,它也解決了我的問題。
add_action('wpcf7_before_send_mail', 'send_form_data_to_wc_session', 5, 1);
function send_form_data_to_wc_session($contact_form) {
$submission = WPCF7_Submission::get_instance();
if($submission) {
$posted_data = $submission->get_posted_data();
if (!empty($posted_data['try'][0])) {
// Set data to Session
session_start();//place this at the top of all code
$_SESSION['cf7_posted_data']=$posted_data;
}
}
}
并檢索:
add_action('woocommerce_checkout_before_customer_details', 'wc_save_cf7_data_to_order', 10, 1);
function wc_save_cf7_data_to_order($order_id) {
session_start();
$posted_data = $_SESSION['cf7_posted_data'];
var_dump($posted_data);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/508466.html
標籤:WordPress 会议 woocommerce 联系表格 7
