This code enables you to add both an event date and time to any product in WooCommerce. Rather than use an events plugin, you can make your own events using this code.
The code adds :
- A custom tab named Event Details
- A custom date field with calendar
- A custom time field with time selection
The code produces these custom fields on the event details tab :

Add the following PHP code to the end of your child themes functions file or custom code snippets plugin.
add_filter('woocommerce_product_data_tabs', 'add_event_tab_1_0');
function add_event_tab_1_0($tabs) {
$tabs['event_tab'] = array(
'label' => __('Event Details', 'woocommerce'),
'target' => 'event_product_data',
'class' => array('show_if_simple', 'show_if_variable'),
'icon' => 'dashicons-calendar-alt',
);
return $tabs;
}
add_action( 'admin_head', 'action_admin_head' );
function action_admin_head() {
echo '<style>
#woocommerce-product-data ul.wc-tabs li a::before {
content: "\f145";
}
</style>';
}
add_action('woocommerce_product_data_panels', 'add_event_fields_to_custom_tab_1_0');
function add_event_fields_to_custom_tab_1_0() {
echo '<div id="event_product_data" class="panel woocommerce_options_panel">';
woocommerce_wp_text_input(
array(
'id' => '_event_date',
'label' => __('Event Date', 'woocommerce'),
'placeholder' => 'YYYY-MM-DD',
'type' => 'date',
)
);
woocommerce_wp_text_input(
array(
'id' => '_event_time',
'label' => __('Event Time', 'woocommerce'),
'placeholder' => 'HH:MM',
'type' => 'time',
)
);
echo '</div>';
}
add_action('woocommerce_admin_process_product_object', 'save_event_date_time_fields_1_0');
function save_event_date_time_fields_1_0($product) {
if (isset($_POST['_event_date'])) {
$product->update_meta_data('_event_date', sanitize_text_field($_POST['_event_date']));
}
if (isset($_POST['_event_time'])) {
$product->update_meta_data('_event_time', sanitize_text_field($_POST['_event_time']));
}
}
add_action('woocommerce_single_product_summary', 'display_event_date_time_1_0', 25);
function display_event_date_time_1_0() {
global $product;
$event_date = $product->get_meta('_event_date');
$event_time = $product->get_meta('_event_time');
if ( ! empty($event_date)) {
echo '<p>' . __('Event Date:', 'woocommerce') . ' ' . esc_html($event_date) . '</p>';
}
if ( ! empty($event_time)) {
echo '<p>' . __('Event Time:', 'woocommerce') . ' ' . esc_html($event_time) . '</p>';
}
}
Leave a Reply