I'm working on a Woocommerce plugin that add some vars in session on "add to cart" action, and use those vars later when order is completed and for the order confirmation email.
Basically the workflow is the following:
-
On
woocommerce_add_to_cartaction, set those session vars.add_filter('woocommerce_add_to_cart', array(&$this->wc, 'add_to_cart'), 10, 1);public function add_to_cart($cart_item_key) { if(!isset($_SESSION['tickets'])) { $_SESSION['tickets'] = array(); } $_SESSION['tickets'][$cart_item_key] = array(); foreach($_POST as $key => $value) { if(preg_match('#^ticket_#', $key)) { $_SESSION['tickets'][$cart_item_key][$key] = $value; } } } -
On
woocommerce_email_after_order_table, use those vars to add informations into the confirmation email.add_action('woocommerce_email_after_order_table', array(&$this->wc, 'email_after_order_table'), 10, 1);public function email_after_order_table($order) { if(isset($_SESSION['tickets']) && !empty($_SESSION['tickets'])) { $output = ''; foreach($_SESSION['tickets'] as $cart_item) { if(is_array($cart_item) && !empty($cart_item)) { foreach($cart_item as $ticket_id) { $ticket = get_post($ticket_id); $room = get_the_term_list($ticket_id, 'product_tag'); $output .= $ticket->post_title . ' (' . $room . ')<br />'; } } } if(!empty($output)) { echo '<h4>' . __('Tickets', 'my-context') . '</h4><p>' . $output . '</p>'; } } }Please note that this action is executed by Woocommerce on the
?wc-ajax=checkoutajax call. On
woocommerce_order_status_completedorwoocommerce_order_status_on-hold, update some CPT using those vars, then delete the session vars.
The problem I have is that when hooking on woocommerce_email_after_order_table $_SESSION is empty. If I look on $_COOKIE['PHPSESSID'], it is set and as the same value as in the context where those session vars are set. And if I try to query the CPT, they aren't updated yet, so the woocommerce_order_status_completed hook (which is working and have no issue accessing the session vars) isn't yet executed.
I tried using WC_Session instead of $_SESSION, it didn't changed anything (step 1 and 3 were working but not step 2).
Does anyone know why the woocommerce_email_after_order_table action isn't in the same context as woocommerce_order_status_completed? Is there any way to pass custom data in that hook?