user10334265
user10334265

Reputation:

Displaying Woocommerce attribute value description instead of value name

I have this code to display product attributes

add_action('woocommerce_single_product_summary', 'attributes', 30 );

function attributes() {
global $product;
$attributes_names = array('Size', 'Color', 'Material', 'Pieces');
$attributes_data  = array();

foreach ( $attributes_names as $attribute_name ) {
    if ( $value = $product->get_attribute($attribute_name) ) {
        $attributes_data[] = $attribute_name . ': ' . $value;
    }
    
}

if ( ! empty($attributes_data) ) {
    echo '<div><p>' . implode( '</p>', $attributes_data ) . '</div>';
}   
}

Instead of displaying the attribute's value, I want to display their description, so something like

$attributes_data[] = $attribute_name . ': ' . $term_description;

How can this be done?

Upvotes: 0

Views: 432

Answers (1)

dilico
dilico

Reputation: 754

You can use wc_get_product_terms to retrieve the terms for a product (including its attributes). The parameters of the function are the product ID, the taxonomy and the query args.

For example, you could do something like this:

function attributes() {
  global $product;

  $attributes_names = array( 'Size', 'Color', 'Material', 'Pieces' );
  $attributes_data = array();
  foreach ( $product->get_attributes() as $attribute => $value ) {
      $attribute_name = wc_get_attribute( $value->get_id() )->name;
      if ( ! in_array( $attribute_name, $attributes_names, true ) ) {
        continue;
      }
      $values = wc_get_product_terms( $product->get_id(), $attribute, array( 'fields' => 'all' ) );
      if ( $values ) {
          $attribute_descriptions = array();
          foreach ( $values as $term ) {
              $attribute_descriptions[] = term_description( $term->term_id, $term->taxonomy );
          }
          $attributes_data[] = $attribute_name . ': ' . implode( ',', $attribute_descriptions );
      }
  }
  if ( ! empty( $attributes_data ) ) {
      echo '<div><p>' . implode( '</p>', $attributes_data ) . '</div>';
  }
}

To note that the attribute description includes any HTML tags, line breaks, etc. That's why in my example above I stripped those, but of course it might not be necessary.

Upvotes: 0

Related Questions