WooCommerce product attributes are a great way of highlighting the major features of a product. Customers use these attributes to make informed decisions.
The problem is that the default page setup doesn’t offer prominent features to display WooCommerce product attributes. In many themes, this section is located so far below that the customers often miss it entirely.
The good news is that showing WooCommerce product attributes on the product display page is very easy. In fact, WooCommerce provides a hook ‘woocommerce_single_product_summary’ to make things easier.
From launching to customizing your WooCommerce stores, Cloudways is at your service.
Whether you’re a beginner or an expert, Cloudways Platform is based on UI, where you can create and customize your online store in a few seconds.
Display Custom Products Attributes
Before going further, note that this code works only for “regular” attributes and not for variations. Â Add this code snippet to the functions.php of your theme:
function cw_woo_attribute(){ global $product; $attributes = $product->get_attributes(); if ( ! $attributes ) { return; } $display_result = ''; foreach ( $attributes as $attribute ) { if ( $attribute->get_variation() ) { continue; } $name = $attribute->get_name(); if ( $attribute->is_taxonomy() ) { $terms = wp_get_post_terms( $product->get_id(), $name, 'all' ); $cwtax = $terms[0]->taxonomy; $cw_object_taxonomy = get_taxonomy($cwtax); if ( isset ($cw_object_taxonomy->labels->singular_name) ) { $tax_label = $cw_object_taxonomy->labels->singular_name; } elseif ( isset( $cw_object_taxonomy->label ) ) { $tax_label = $cw_object_taxonomy->label; if ( 0 === strpos( $tax_label, 'Product ' ) ) { $tax_label = substr( $tax_label, 8 ); } } $display_result .= $tax_label . ': '; $tax_terms = array(); foreach ( $terms as $term ) { $single_term = esc_html( $term->name ); array_push( $tax_terms, $single_term ); } $display_result .= implode(', ', $tax_terms) . '<br />'; } else { $display_result .= $name . ': '; $display_result .= esc_html( implode( ', ', $attribute->get_options() ) ) . '<br />'; } } echo $display_result; } add_action('woocommerce_single_product_summary', 'cw_woo_attribute', 25);
Note: Place the above code in functions.php, located in your theme folder.
you have to check the attribute by using var_dump();
global $product; $attributes = $product->get_attributes(); var_dump($attributes);
The Output of the Code
This is what the output of this code looks like:
Summary
Displaying WooCommerce product attributes on product pages is a great way of encouraging customers to make purchases. If you need help implementing this code at your WooCommerce store, leave a comment, and I will get back to you.
Owais Alam
is the WordPress Community Manager at Cloudways - A Managed WooCommerce Hosting Platform and a seasoned PHP developer. He loves to develop all sorts of websites on WordPress and is in love with WooCommerce in particular. You can email him at [email protected]