我試圖在物品添加到購物車時將其設置爲元數據,通過每個頁面重新加載並在檢出成功時檢索元數據以傳遞給一個獨立的API。在物品上保留元數據,並在結帳時檢索完成
下面的代碼在頁面重新加載後迴應元數據,因此我認爲這是成功的。
add_action('woocommerce_order_status_completed', 'order_system');
add_filter('woocommerce_add_cart_item_data', 'nick_add_cart_item_data', 10, 2);
add_filter('woocommerce_get_cart_item_from_session', 'nick_get_cart_item_from_session', 10, 2);
function nick_add_cart_item_data($cart_item_meta, $product_id) {
global $woocommerce;
$nick_form_data = get_post_meta($product_id, '_nick_form_data', true);
$cart_item_meta['_nick_form_data'] = $nick_form_data;
$cart_item_meta['_nick_credential_data']['username'] = (isset($_POST['username']) && $_POST['username'] != '') ? $_POST['username'] : '';
$cart_item_meta['_nick_credential_data']['password'] = (isset($_POST['password']) && $_POST['password'] != '') ? $_POST['password'] : '';
return $cart_item_meta;
}
function nick_get_cart_item_from_session($cart_item, $values) {
if (isset($values['_nick_form_data'])) {
$cart_item['_nick_form_data'] = $values['_nick_form_data'];
}
if (isset($values['_nick_credential_data'])) {
$cart_item['_nick_credential_data'] = $values['_nick_credential_data'];
echo $values['_nick_credential_data']['username'] . $values['_nick_credential_data']['password'] ;
}
return $cart_item;
}
當我調用此函數,當訂單完成時觸發,我無法保留任何項目元數據。
function order_system($order_id)
{
global $woocommerce;
try {
// do something that can go wrong
// instantiate new order from WooCommerce
$order = new WC_Order($order_id);
$userid = $order->user_id;
foreach ($order->get_items() as $item_id => $values) :
if (isset($values['_nick_form_data'])) :
// Not getting inside this case statement
endif;
endforeach;
....
我不確定我做錯了什麼,任何幫助表示讚賞。謝謝!!
謝謝,這個答案救了我 –
「有點晚」從來沒有這麼委婉:D:D –