This guide shows you how you can create a custom Select field type in the product editor of WooCommerce. A select field (or drop-down list) is useful when you want to allow only one option from a predefined selection of options. Tax Status is an example existing field which uses the select field type for products. This guide also shows you how you can output the value selected and saved from the product editor on the front-end.
/**
* Snippet Name: WooCommerce Custom Product Drop-down list Metabox
* Snippet Author: ecommercehints.com
*/
// Create the custom product select metabox
add_action ('woocommerce_product_options_advanced', 'ecommercehints_custom_product_select_metabox');
function ecommercehints_custom_product_select_metabox() {
echo '';
woocommerce_wp_select(array ( // A select type field
'id' => 'custom_product_select_metabox',
'value' => get_post_meta (get_the_ID(), 'custom_product_select_metabox', true),
'label' => 'Custom Select Field Label',
'description' => 'This is the description',
'desc_tip' => true, // If true, place description in question mark tooltip.
'options' => array(
'option_1' => 'Option 1',
'option_2' => 'Option 2',
'option_3' => 'Option 3'
),
));
echo '';
}
// Save data selected on update
add_action ('woocommerce_process_product_meta', 'ecommercehints_save_field_on_update', 10, 2);
function ecommercehints_save_field_on_update ($id, $post) {
update_post_meta ($id, 'custom_product_select_metabox', $_POST['custom_product_select_metabox']);
}
How Do I Get The Custom Select Field Data?
global $product;
$custom_product_select_metabox = $product->get_meta ('custom_product_select_metabox');
echo $custom_product_select_metabox;