The WooCommerce 3.0 update has not been kind to me. I have added a custom required field to checkout for a domain name, and am having trouble figuring out how to get it to save now. This code adds the field properly still:
add_action( 'woocommerce_after_order_notes', 'add_domain_checkout_field' );
function add_domain_checkout_field( $checkout ) {
echo '<div id="add_domain_checkout_field"><h2>' . __('Domain') . '</h2>';
woocommerce_form_field( 'sitelink_domain', array(
'type' => 'text',
'required' => true,
'class' => array('my-field-class form-row-wide'),
'label' => __('Domain where SiteLink will be installed'),
'placeholder' => __('Enter your URL'),
), $checkout->get_value( 'sitelink_domain' ));
echo '</div>';
}
And I am trying to save it, this way:
add_action( 'woocommerce_checkout_create_order', 'add_domain_to_order_meta', 10, 2 );
function add_domain_to_order_meta( $order, $data ) {
if ( ! empty( $_POST['sitelink_domain'] ) ) {
$order->add_meta_data( 'ssla_sitelink_url', sanitize_text_field( $_POST['sitelink_domain'] ) );
}
}
However the meta does not appear to be added or saved anywhere.
I know that the $_POST
variable is there, I have error logged it out to see.
Testing some grabbing and error logging confuses me further:
$sitelink_domain = $subscription->get_meta_data( 'ssla_sitelink_url' );
error_log( print_r( $sitelink_domain, true ) );
// Output is:
[21-Apr-2017 01:26:27 UTC] Array
(
[0] => stdClass Object
(
[id] => 270086
[key] => _ssla_sitelink_url
[value] => lololol.com
)
[1] => stdClass Object
(
[id] => 270089
[key] => _download_permissions_granted
[value] => 1
)
)
However,
$sitelink_domain = $subscription->get_meta( 'ssla_sitelink_url' );
error_log( 'Domain: ' . $sitelink_domain );
Output is just:
[21-Apr-2017 01:27:39 UTC] Domain:
First you need to validate the field when the checkout form is posted and the field is required and not optional using
woocommerce_checkout_process
action hook:As this is a checkout custom field, you can use
woocommerce_checkout_update_order_meta
action hook to save the new field to order custom fields:Use
woocommerce_admin_order_data_after_billing_address
action hook to display the custom field value on the admin order edition page:Display the custom field label and value in frontend orders and email notifications:
This code goes in function.php file of your active child theme (or theme) or also in any plugin file.
This code works for WooCommerce 3.0+
You may add additional order meta data like below.