php - 显示 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;
如何才能做到这一点?
解决方案
您可以使用它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 标记、换行符等。这就是为什么在我上面的示例中我剥离了这些,但当然这可能不是必需的。
推荐阅读
- python - Pythonic 使用排序函数的方法
- c# - Streamwriter 未将命令正确写入网络流
- python - github存储库中的json文件是否需要时间来更新?
- flutter - Dart / Flutter:使用基对象中的 fromJson 将 json 映射到具有基类的对象
- matlab - 为什么空数组可以有非空维度?
- azure - 如何根据 JSON 模式验证 JSON 源?
- python - 如何仅记录 Sphinx 中的一部分功能?
- html - 如何使可滚动表格占容器剩余宽度的 100%,而不是屏幕?
- spring - 如何设置 Spring Data JPA 存储库?
- c# - 在 .Net xUnit 项目中,当我运行测试时,我收到“程序不包含静态‘主’”错误,因为我引用了其他项目将被测试