This snippet adds a product time picker to the single product template above the add to cart button and save the time picked against the product as meta data. Once a time is picked against the product, you’ll notice it is shown under the product name in the mini-cart, cart, checkout, thank you page, emails, my account area, and order view in the admin dashboard. This is a rather niche requirement and a lot of use cases would require a time picker on the checkout rather than the product page. This particular snippet is useful if you need to set a time against a product. Arrival time, tattoo, and engraving are some example of where a time may need to be picked against a product.
/**
* Snippet Name: WooCommerce Product Time Picker
* Snippet Author: ecommercehints.com
*/
// Add the new field
add_action( 'woocommerce_before_add_to_cart_button', 'ecommercehints_custom_product_time_picker_field' );
function ecommercehints_custom_product_time_picker_field() {
global $product;
echo '
';
}
// Save the field to the cart data
add_filter( 'woocommerce_add_cart_item_data', 'ecommercehints_save_custom_time_to_cart_data', 10, 3 );
function ecommercehints_save_custom_time_to_cart_data( $cart_item_data, $product_id, $variation_id ) {
if ( !empty( $_POST['arrival-time'] ) ) {
$cart_item_data['arrival-time'] = $_POST['arrival-time'];
}
return $cart_item_data;
}
// Show custom field data on cart, checkout, and thank you page.
add_filter( 'woocommerce_get_item_data', 'ecommercehints_show_custom_time_data_under_product_name', 10, 2 );
function ecommercehints_show_custom_time_data_under_product_name( $item_data, $cart_item ) {
if ( !empty( $cart_item['arrival-time'] ) ) {
$item_data[] = array(
'key' => 'Team arrival time',
'value' => $cart_item['arrival-time'],
);
}
return $item_data;
}
// Save the custom field data as order meta
add_action( 'woocommerce_checkout_create_order_line_item', 'ecommercehints_add_custom_time_data_as_product_meta', 10, 4 );
function ecommercehints_add_custom_time_data_as_product_meta( $item, $cart_item_key, $values, $order ) {
if ( !empty( $values['arrival-time'] ) ) {
$item->add_meta_data( 'Team arrival time', $values['arrival-time'] );
}
}