I’m attempting to save a simple text input to the WooCommerce session. The session is created when a user adds something to their cart.
My input field exists in custom page template that will be placed in the user flow after the cart but before the checkout: cart > my template > checkout.
So far
Simple form to capture data (custom template file)
<form name="group" method="post" class="checkout woocommerce-checkout" action="http://localhost:/site.dev/my-template">
<div class="group-order">
<p class="form-row form-row woocommerce-validated" id="create_new_group_field">
<label for="create_new_group" class="">Join an existing group</label>
<input type="text" class="input-text " name="create_new_group" id="create_new_group">
</p>
</div>
</form>
Receiving and setting data (I’m having trouble figuring out when/how to run this. in my custom page)
UPDATE
I’ve added the code below to the top of my page template so the page processes itself and then re-directs to the checkout.
function set_and_save_input_to_session() {
if( !is_admin( ) ) {
// User input
if( ! empty( $_POST['create_new_group'] ) ) {
$group_input_value = $_POST['create_new_group'];
// Set session and save data
WC()->session->set( 'group_order_data', $group_input_value );
wp_redirect( 'http://localhost:28/site.dev/checkout' );
exit();
}
}
get_header();
add_action(‘woocommerce_checkout_process’, ‘set_and_save_input_to_session’);
Retrieving and saving data
function retrieve_and_save_group_input_value_to_order_meta() {
$retrived_group_input_value = WC()->session->get( 'group_order_data' );
update_post_meta( $order_id, '_create_new_group', $retrived_group_input_value );
}
add_action('woocommerce_checkout_update_order_meta', 'retrieve_and_save_group_input_value_to_order_meta');
I’m currently working my way through what are to me, more complex solutions and therefore I’d appreciate if anyone could point out any major flaws with my process so far.
UPDATE
I can confirm that the form is receiving data and that the WC()->session->set
is setting data. (Thanks to @Firefog for suggesting the use the $_SESSION
global)
After further investigation and finding the right place to var_dump
the session data I found that the data was being set to the session with my original method.
The data is set, but I can’t see why the data won’t save to the order.
It’s more saying Thank you for solving my problem. But here is an answer, too:
The post meta could not been updated because there is no
$order_id
parameter in your callback function. This should do the trick:Here is another approach.
1st page:
Now in another page write the following to receive the value: