Enhance Your WooCommerce Product Listings: Adding Attributes to Product Loop Items

In WooCommerce, product attributes are vital in describing product characteristics and helping customers make informed purchasing decisions. Adding attributes to product loop items can provide users with essential product information from the shop or category pages. In this guide, we’ll walk you through displaying attributes alongside product thumbnails in the product loop.

Step 1: Add attribute after loop title custom Function
/**
* Snippet Name: Adding attribute after loop title
* Snippet Author:	wpsnippets.dev
*/

//Display product attributes on product loop items 
function wps_display_attributes_on_product_loop() {
    global $product;

    $attributes = $product->get_attributes();

    if ( $attributes ) {
        echo '<ul class="wps-product-attributes">';

        foreach ( $attributes as $attribute ) {
            $attribute_label = wc_attribute_label( $attribute->get_name() );
            $attribute_value = $product->get_attribute( $attribute->get_name() );

            if ( $attribute_value ) {
                echo '<li><strong>' . esc_html( $attribute_label ) . ':</strong> ' . wp_kses_post( $attribute_value ) . '</li>';
            }
        }

        echo '</ul>';
    }
}

add_action( 'woocommerce_after_shop_loop_item_title', 'wps_display_attributes_on_product_loop', 15 );

Step 2: Style the attribute with CSS
.wps-product-attributes{
	margin: 0px;
	list-style: none;
    margin-bottom: 1em;
}

Code Explanation

  • This code snippet utilizes the woocommerce_before_shop_loop_item_title action hook to add a function that displays product attributes before each product title in the product loop.
  • It retrieves the product’s attributes using $product->get_attributes() and iterates through them to display each attribute’s label and value.
  • The function code goes under the function.php file, and the CSS part goes under the style.css file of your child theme.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top