Trends

How to add custom checkout fields in Woo-commerce ?

To add custom fields to the WooCommerce checkout page, you can use hooks and filters provided by WooCommerce. Here's a step-by-step guide on how to add custom fields to the WooCommerce checkout page:

1. Create a child theme (recommended):
   - If you haven't already, create a child theme for your WordPress website. This is important to prevent your changes from being overwritten during theme updates. If you're already using a child theme, you can skip this step.

2. Open your child theme's `functions.php` file:
   - In your child theme folder, locate the `functions.php` file and open it in a text editor.

3. Add the custom field using the `woocommerce_checkout_fields` filter:
   - Inside the `functions.php` file, add the following code to add a custom field to the WooCommerce checkout page:

function custom_woocommerce_checkout_fields($fields) {
    $fields['extra_field'] = array(
        'label'       => __('Custom Field', 'woocommerce'),
        'required'    => true,
        'class'       => array('form-row-wide'),
        'clear'       => true,
        'priority'    => 150,
    );

    return $fields;
}
add_filter('woocommerce_checkout_fields', 'custom_woocommerce_checkout_fields');
```

4. Save the changes:
   - Save the `functions.php` file.

5. Test the custom field:
   - Open the checkout page of your WooCommerce website and verify that the custom field is displayed.

6. Access the custom field value:
   - To access the value of the custom field submitted by the user, you can use the `woocommerce_checkout_create_order` or `woocommerce_checkout_update_order_meta` hook. For example:

function save_custom_field($order_id) {
    $custom_field_value = isset($_POST['extra_field']) ? sanitize_text_field($_POST['extra_field']) : '';
    if (!empty($custom_field_value)) {
        update_post_meta($order_id, 'Custom Field', $custom_field_value);
    }
}
add_action('woocommerce_checkout_create_order', 'save_custom_field', 10, 1);
```

This code snippet saves the custom field value as order meta data. You can modify it to suit your needs.

That's it! You've successfully added a custom field to the WooCommerce checkout page using hooks and filters. Remember to test the field thoroughly to ensure it functions as expected.

No comments