我试图在将项目添加到购物车时为其设置元数据,在每次重新加载页面时将其保留,并在结帐成功时检索元数据以传递给单独的 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;
....
我不确定我做错了什么,任何帮助表示赞赏。谢谢!!