I can add a custom variable to a WooCommerce order, using code like this – but only if the code is on the product page:
<form action="<?php echo esc_url( wc_get_checkout_url() ); ?>" method="post">
<?php
$value = isset( $_POST['dogname'] ) ? sanitize_text_field( $_POST['dogname'] ) : '';
echo '<div><label>Name of Dog</label><p><input name="dogname" value="' . $value . '"></p></div>';
?> <button type="submit">Checkout</button>
</form>
But how do I add the data to the order it if I am not on the product page? I redirect the page after add to cart to a custom page. On this custom page the cart is already populated with the product . But submitting this form on the custom page – goes to checkout but does not update or add the variable to the order. How would I update the order with my custom variable from my custom page?
Maybe I need some extra code for the button to update the order on click?
What code would I use for a button – that on click would post the form values to my order, and direct to another page?
2
Answers
To add some more functionality to LoicTheAztec answer using his
thankyou_display_dog_data
function. His included action shows the function on thank you after checkout formHere below is a way to get posted data available in checkout page and anywhere else without loosing this posted data. For that we set the posted data to a WC session variable, so this posted data is available at any moment when needed.
The form on your page (example with multiple fields):
The code that set the posted data to a
WC_Session
variable:Code goes in functions.php file of the active child theme (or active theme). Tested and works.
Then you can get that data on any function or template with:
Save that data to order details:
Code goes in functions.php file of the active child theme (or active theme).
Then you can get that data from The WC_Order object order using:
Like in this hooked function that will display data on "Order received" page:
Tested and works on last WooCommerce version.