As it happens, I just blogged about this yesterday, for how to add a subscribe to mailing list checkbox. The key points are:
- look at the WooCommerce tutorial
- woocommerce_checkout_fields is a filter hook that allows you to add or modify what fields appear on the checkout form
- woocommerce_checkout_update_order_meta is an action hook that allows you to save your new fields
- woocommerce_email_order_meta_keys is a filter hook that allows you to add your new fields to the confirmation emails
- the name you pick to save the post meta will be its label in the email
Here’s the code I used:
class WooSubscribeCheckbox {
// add hooks into WooCommerce
public static function run() {
add_filter('woocommerce_checkout_fields',
array(__CLASS__, 'filterWooCheckoutFields'));
add_action('woocommerce_checkout_update_order_meta',
array(__CLASS__, 'actionWooCheckoutUpdateOrderMeta'));
add_filter('woocommerce_email_order_meta_keys',
array(__CLASS__, 'filterWooEmailOrderMetaKeys'));
}
/**
* add custom fields to WooCommerce checkout
* @param array fields
* @return array
*/
public static function filterWooCheckoutFields($fields) {
global $woocommerce;
// add field at end of billing fields section
$fields['billing']['our_mailing_subscribe'] = array(
'type' => 'checkbox',
'label' => 'Subscribe to mailing list?',
'placeholder' => 'Subscribe to mailing list',
'required' => false,
'class' => array(),
'label_class' => array(),
);
return $fields;
}
/**
* save custom order fields
* @param int $order_id
*/
public static function actionWooCheckoutUpdateOrderMeta($order_id) {
if (isset($_POST['our_mailing_subscribe'])) {
update_post_meta($order_id, 'Subscribe to mailing list',
stripslashes($_POST['our_mailing_subscribe']));
}
}
/**
* add our custom fields to WooCommerce order emails
* @param array $keys
* @return array
*/
public static function filterWooEmailOrderMetaKeys($keys) {
$keys[] = 'Subscribe to mailing list';
return $keys;
}
}
WooSubscribeCheckbox::run();