Display Product Attribute on Shop Page in WooCommerce

Use this code snippet to display a product attribute on the shop page in WooCommerce on child sites.

Snippet Type

Execute on Child Sites

Snippet

add_action( 'woocommerce_after_shop_loop_item_title', 'display_size_attribute', 5 );
function display_size_attribute() {
    global $product;

    if ( $product->is_type('variable') ) {
        $taxonomy = 'pa_size';
        echo '<span class="attribute-size">' . $product->get_attribute($taxonomy) . '</span>';
    }
}
1 Like

Thank you for this! If I want to achieve the same result on the product page, would I be best adapting this snippet, or adding a separate variation in addition to this one?

1 Like

I would adapt the existing code snippet but target just the product page.

Thanks so much for your reply. The thing that has tripped me up is that (as far as I can determine) on single product pages I’d need to first remove the default 'woocommerce_single_product_summary' which doesn’t apply on the shop loop.

Sorry I’ve just realised that my initial post wasn’t clear: I’d like to display the attribute beneath the product title on both the shop loop and single product pages.

This is the code I’m using for the loop, but I’d like to adapt it to also apply on product pages:

add_action( 'woocommerce_after_shop_loop_item_title', 'display_book_author_attribute', 5 );
function display_book_author_attribute() {
    global $product;

    if ( $product->is_type('simple') ) {
        $taxonomy = 'pa_book_author';
        echo '<span class="attribute-book_author">' . $product->get_attribute($taxonomy) . '</span>';
    }
}

Sorry to be so convoluted, and thank you again!

One moment I will create another code snippet and share it.

Try this.

add_action( 'woocommerce_after_shop_loop_item_title', 'display_book_author_attribute', 5 );
add_action( 'woocommerce_single_product_summary', 'display_book_author_attribute', 5 );
function display_book_author_attribute() {
    global $product;

    if ( $product->is_type('simple') ) {
        $taxonomy = 'pa_book_author';
        echo '<span class="attribute-book_author">' . $product->get_attribute($taxonomy) . '</span>';
    }
}

Example.
Product attribute test show

Related