George Gour
George Gour

Reputation: 65

Display specific product attribute linked terms set for a WooCommerce product

A product has for example an attributes pa_color with 3 values ("silver", "red" and "brown"). I would like to show three dynamic links to its description.

I would like to show to my product this text:
"This product has these three colors: Silver(html link), Red(html link), Brown(html link)"

i managed to do this if it has one attribute:

if ( is_product() && has_term( 'Silver', 'pa_color' ) ) {

}

Upvotes: 1

Views: 439

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253868

Use the following code that will display the attribute liked colors set for a product:

$taxonomy = 'pa_color'; // Here set the product attribute taxonomy
$terms    = wp_get_post_terms( get_the_ID(), $taxonomy ); // Get the terms

if ( ! empty( $terms ) ) {
    $output   = []; // Initializing

    // Loop through the terms set in the product
    foreach( $terms as $term ) {
        $output[] = '<a href="'.get_term_link( $term, $taxonomy ).'">'.$term->name.'</a>';
    }
    // Display
    printf( __("This product has these %s %s: %s."),  count($terms),
    _n( "color", "colors", count($terms) ), implode( ', ', $output ) );
}

Tested and works.

Upvotes: 2

Related Questions