Getting the custom checkout field value in Woocommerce is one of the common queries that most developers face while creating an e-commerce website. A checkout page is an essential part of every online shopping store. It’s that point where the customer’s details are collected, and payment is received; this is why it is important to have the checkout page customized to match your business’s specific needs. With Woocommerce, it’s easy to add custom fields to your checkout pages. In this blog, we are going to guide you through how to get the custom checkout field value in Woocommerce.
Woocommerce is a popular plugin to develop an online e-commerce store. It gives you the ability to customize your website the way you want it. One option of customizing your website is by adding woocommerce custom checkout fields. If you’ve already added these fields, you can use the following code to extract the value entered by users.
To extract the value of custom checkout fields from Woocommerce, we will first have to obtain the corresponding order’s details object.
The Woocommerce checkout field and order object is located in the $order global variable, which can be fetched using the following code.
$order = WC()->session->get(‘order_awaiting_payment’);
$order = new WC_Order($order);
After we obtain the order object, we can get the values for the custom checkout fields. Below is an example to retrieve custom checkout fields in Woocommerce.
$gender = $order->get_meta(‘gender’);
This example is for a custom field with the name ‘gender’. The field’s value is stored in the Woocommerce order meta and can be accessed using the `get_meta()` function. You can replace “gender” with your custom checkout field name to fetch that specific field.
Similarly, you can use this code to retrieve multiple fields using the `get_meta()` function.
$first_name = $order->get_meta(‘billing_first_name’);
$phone_number = $order->get_meta(‘billing_phone’);
The code above gets two different custom checkout fields, first_name and phone_number.
The Woocommerce custom checkout fields have three positions. They can be added to your billing section, shipping section, or order notes. Depending on the location of your custom field, add the appropriate prefix to extract the correct value. For example, if it is a billing field, you can use the ‘billing_’ prefix, and if it is a shipping field, use the ‘shipping_’ prefix.
In conclusion, adding custom fields to the checkout page using Woocommerce is a great way to add additional information to increase the store customer experience. Retrieving the data is easy using the instructions above. We hope this blog helped you correctly retrieve the custom checkout field value in Woocommerce. If you have any further questions, you can contact us through our website, and we will be happy to assist you.