I have an url to woocommerce checkout, with variables to put into the billing fields automatically, so they should not be shown at the checkout page. How can we do so?
Adding type="hidden"
to the input fields?
Thanks.
I have an url to woocommerce checkout, with variables to put into the billing fields automatically, so they should not be shown at the checkout page. How can we do so?
Adding type="hidden"
to the input fields?
Thanks.
We should minimize "user involvement" as much as we can (removing type=hidden
is a very easy thing to do), so if you have data that should be automatically added, I would advise you to disable those fields completely and insert data via WooCommerce filters.
First filter that you need is woocommerce_billing_fields
. With that filter, you can remove or add fields. It accepts one argument, and that's array of billing fields. For example:
/**
* Used to remove WooCommerce billing fields
*
* @param array $fields
*
* @return array Modified billing fields
*/
function so_remove_billing_fields( $fields ){
// FYI: These are all default WooCommerce billing fields
// (remove those which need to stay)
$fields_to_remove = array(
'billing_first_name',
'billing_last_name',
'billing_company',
'billing_address_1',
'billing_address_2',
'billing_city',
'billing_postcode',
'billing_country',
'billing_state',
'billing_email',
'billing_phone',
);
foreach( $fields_to_remove as $field ){
unset( $fields[$field] );
}
return $fields;
}
add_filter( 'woocommerce_billing_fields', 'so_remove_billing_fields' );
We should now save the custom data to the post (order) meta, and for that, we will use woocommerce_checkout_update_order_meta
filter. It has one argument, and that is integer order ID. For example:
/**
* Save custom data to the database
*
* @param int $order_id
*
* @return void
*/
function so_add_billing_fields_data( $order_id ){
$data_to_add = array(
'field_name' => apply_filters( 'so_custom_field_name_data', null ),
);
foreach( $data_to_add as $field_name => $data ){
if ( ! empty( $data ) )
update_post_meta( $order_id, $field_name, sanitize_text_field( $data ) );
}
}
add_filter( 'woocommerce_checkout_update_order_meta', 'so_add_billing_fields_data' );
Maybe sanitize_text_field()
was not necessary here, but better safe than sorry. I don't know the source of your data. ;)
By the way, I opted for apply_filters
in this example to add data to the array, but if you can also gather data in this function and put it into a variable.
See more: WooCommerce: Customizing checkout fields | WordPress: Filter API Reference | Validating Sanitizing and Escaping User Data