自定义WooCommerce模板:在附加信息页展示商品属性术语描述
自定义WooCommerce商品属性术语描述展示实现
修改思路
- 仅处理全局商品属性,这类属性的取值为分类术语,自带描述字段;产品级自定义文本属性无对应术语描述,直接跳过
- 读取当前产品关联的属性术语,筛选非空描述后输出
- 兼容WooCommerce默认属性表格的两列布局,不破坏原有样式
原代码中计划插入的第三列单元格会破坏默认两列表格布局,因此调整展示位置为属性值下方或跨列整行。
完整修改后模板代码
defined( 'ABSPATH' ) || exit; if ( ! $product_attributes ) { return; } global $product; ?> <table class="woocommerce-product-attributes shop_attributes"> <?php foreach ( $product_attributes as $product_attribute_key => $product_attribute ) : $taxonomy = $product_attribute['name']; $term_descriptions = []; // 仅处理存在对应分类法的全局属性 if ( taxonomy_exists( $taxonomy ) ) { $terms = get_the_terms( $product->get_id(), $taxonomy ); if ( $terms && ! is_wp_error( $terms ) ) { foreach ( $terms as $term ) { if ( ! empty( $term->description ) ) { $term_descriptions[] = wp_kses_post( $term->description ); } } } } ?> <tr class="woocommerce-product-attributes-item woocommerce-product-attributes-item--<?php echo esc_attr( $product_attribute_key ); ?>"> <th class="woocommerce-product-attributes-item__label"><?php echo wp_kses_post( $product_attribute['label'] ); ?></th> <td class="woocommerce-product-attributes-item__value"> <?php echo wp_kses_post( $product_attribute['value'] ); ?> <?php if ( ! empty( $term_descriptions ) ) : ?> <div class="woocommerce-product-attributes-item__description" style="margin-top: 0.5em; font-size: 0.9em; opacity: 0.8;"> <?php echo implode( '<br>', $term_descriptions ); ?> </div> <?php endif; ?> </td> </tr> <?php endforeach; ?> </table>
可选调整:描述单独占整行
如果不想将描述放在属性值下方,想要单独跨满两列展示,可将值单元格内的描述代码移除,在对应属性行的</tr>之后添加以下代码:
<?php if ( ! empty( $term_descriptions ) ) : ?> <tr class="woocommerce-product-attributes-item woocommerce-product-attributes-item--term-description"> <td colspan="2" class="woocommerce-product-attributes-item__description" style="padding: 0 0 1em 0; font-size: 0.9em; opacity: 0.8;"> <?php echo implode( '<br>', $term_descriptions ); ?> </td> </tr> <?php endif; ?>
生效条件
- 对应属性必须是全局商品属性(在WooCommerce属性管理页提前创建的属性,而非编辑单个产品时手动输入的自定义文本属性)
- 术语描述需在「产品→属性→对应属性→编辑术语」页面填写,留空则自动不展示
- 修改后的模板需放置在当前主题的
woocommerce/single-product/product-attributes.php路径下,覆盖默认模板
内容的提问来源于stack exchange,提问作者user5135
相关产品推荐
相关产品推荐

