首页 > 解决方案 > 显示 Woocommerce 属性值描述而不是值名称

问题描述

我有这个代码来显示产品属性

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>';
}   
}

而不是显示属性的值,我想显示他们的描述,所以像

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

如何才能做到这一点?

标签: phpwordpresswoocommerce

解决方案


您可以使用它wc_get_product_terms来检索产品的术语(包括其属性)。该函数的参数是产品 ID、分类和查询参数。

例如,您可以执行以下操作:

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>';
  }
}

请注意,属性描述包括任何 HTML 标记、换行符等。这就是为什么在我上面的示例中我剥离了这些,但当然这可能不是必需的。


推荐阅读