add_action( 'woocommerce_before_add_to_cart_button', 'sizes_before_add_to_cart_button', 0 );
function sizes_before_add_to_cart_button() {
global $product;
// Only on simple products
if( ! $product->is_type('simple') ) return;
// When product sizes are available
if ( $sizes = $product->get_attribute( 'size' ) ) :
$sizes = explode(", ",$sizes);
echo '<div class="lisatiedot__size__select" id="product-size-field">
<label for="product-size">' . __('Valitse koko <br>') . '</label>
<select class="select__size" name="product-size" id="product-size">
<option value="">' . __("Choose your size") . '</option>';
foreach( $sizes as $size ){
echo '<option value="' . $size . '">' . $size . '</option>';
}
echo '</select>
</div><br>';
endif;
}
add_filter( 'woocommerce_add_to_cart_validation', 'filter_add_to_cart_validation', 10, 4 );
function filter_add_to_cart_validation( $passed, $product_id, $quantity, $variation_id = 0 ) {
$product = wc_get_product($product_id);
// Only on simple products and When product sizes are available
if( ! $product->is_type('simple') && ! $product->get_attribute( 'size' ) )
return $passed;
if( isset( $_POST['product-size'] ) && empty( $_POST['product-size'] ) ) {
wc_add_notice( __("Please choose your size.", "woocommerce" ), 'error' );
$passed = false;
}
return $passed;
}
add_filter( 'woocommerce_add_cart_item_data', 'add_size_to_cart_item_data', 10, 3 );
function add_size_to_cart_item_data($cart_item_data, $product_id, $variation_id ){
if( isset( $_POST['product-size'] ) ) {
$cart_item_data['product-size'] = esc_attr( $_POST['product-size'] );
}
return $cart_item_data;
}
add_filter( 'woocommerce_get_item_data', 'display_size_on_cart_item', 10, 2 );
function display_size_on_cart_item( $cart_item_data, $cart_item ) {
if ( isset( $cart_item['product-size'] ) ){
$cart_item_data[] = array(
'name' => __('Size'),
'value' => $cart_item['product-size'],
);
}
return $cart_item_data;
}