简体   繁体   English

结帐后是否有Woocommerce会话?

[英]Availability of Woocommerce Session after checkout?

I'm currently using a Woocommerce session to save information that the user inputs on the cart page which affects a fee added to the transaction. 我目前正在使用Woocommerce会话来保存用户在购物车页面上输入的信息,这会影响添加到交易中的费用。

I need to be able to access this information right after the order has been completed to make necessary updates to the user's account. 我需要能够在订单完成后立即访问此信息,以对用户帐户进行必要的更新。

I figured woocommerce_thankyou would be a good hook to use, but unfortunately the session only seems to be available half of the time. 我认为woocommerce_thankyou可以很好地使用,但是不幸的是,该会话似乎只有一半时间可用。

Are there any better hooks to use where I could confirm that the purchase had been completed and the session information would be available? 在我可以确认购买已完成并且可以获取会话信息的地方,还有更好的选择吗?

You need to save that session data as custom order meta data , to be able to use it afterwards (replace my_key , in the code below, with the correct session key): 您需要将该会话数据另存为自定义订单元数据 ,以便以后使用(将下面的代码中的my_key替换为正确的会话密钥):

// Add custom order meta data with temporary data from WC_Session
add_action( 'woocommerce_checkout_create_order', 'add_session_data_as_custom_order_meta_data', 10, 2 );
function add_session_data_as_custom_order_meta_data( $order, $data ) {
    if ( $session_data = WC()->session->get('my_key') ) {
         $order->update_meta_data( '_session_data', $session_data );
    }
}

Code goes on function.php file of your active child theme (or theme). 您的活动子主题(或主题)的function.php文件中包含代码。 Tested and works. 经过测试和工作。


Then to access the data you will use th WC_Data method get_meta() on the WC_Order Object: 然后,要访问数据,您将在WC_Order对象上使用WC_Data方法get_meta()

$session_data = $order->get_meta('_session_data');

Or also using get_post_meta() function from a defined order Id : 或者也可以从已定义的订单ID使用get_post_meta()函数:

$session_data = get_post_meta( $order_id, '_session_data', true );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM