Wordpress
Add Custom Attributes Dropdown to WooCommerce Product Page
Written by Abhilash Sahoo•Updated on July 8, 2023•3 min read
WooCommerce product attributes let you define extra product data, such as size or colour to help customers know more about the product. The default Woocommerce template does have the features to display it in the additional information section but if you are looking to show it just above the cart button then you can use the WooCommerce hook woocommerce_before_add_to_cart_button. This is the best way to show custom product attributes on the shop page programmatically.
Display Custom Products Attributes Dropdown
The following code will work only for simple product or if you are using WooCommerce lottery. To show a list, select or a dropdown for all the custom attributes in the frontend just above the cart button you can add the code to functions.php file of the current theme you are using.add_action('woocommerce_before_add_to_cart_button', 'custom_product_attributes'); function custom_product_attributes() { global $product; $attributes = $product->get_attributes(); if ( ! $attributes ) { return; } if ($product->is_type( 'variable' )) { return; } echo '<div class="wc-prod-attributes"><h2>Custom Attributes</h2>'; foreach ( $attributes as $attribute ) { $attribute_data = $attribute->get_data(); $attribute_terms = $attribute_data['options']; $label = $attribute_data['name']; ?> <div class="wc-prod-single-attribute"> <h3><?php echo $label; ?></h3> <select class="wc-custom-select-attribute" name="attribute[<?php echo $attribute_data['id']; ?>]" id="attribute[<?php echo $attribute_data['id']; ?>]"> <option value selected>Choose an option</option> <?php foreach ( $attribute_terms as $pa ): ?> <option value="<?php echo $pa; ?>"><?php echo $pa; ?></option> <?php endforeach; ?> </select> </div> <?php } echo '</div>'; } ?>Note: Don't place the code in the woocommerce plugin folder. It is always advised to place the above code in functions.php of the theme you are using so that the files don't overwrite when you update WooCommerce plugin.