我试图在将商品添加到购物车时设置其元数据,并在每次页面重新加载时将其保留,并在结帐成功后检索元数据以传递给单独的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;
....
我不确定自己做错了什么,我们将不胜感激.谢谢!!
解决方法:
有点晚了,但是:尽管您将元数据附加到购物车项目,但是在创建订单时,它们不会随后添加到订单项中.要做到这一点:
function nick_add_order_item_meta($itemID, $values) {
$nick_form_data = $values['_nick_form_data'];
if (!empty($nick_form_data)) {
wc_add_order_item_meta($itemID, '_nick_form_data', $nick_form_data);
}
}
add_action('woocommerce_add_order_item_meta','nick_add_order_item_meta', 1, 2);
在创建订单时,购物车商品meta _nick_form_data将附加到每个商品.然后,当您查看订单时,便可以在WooCommerce的后端中看到它:每个订单项旁边都应有一个[?],这将向您显示附加的元数据.