我需要在 WordPress 网站的每个产品卡上显示自定义属性。 我使用了一个 php 函数:
add_action( 'woocommerce_shop_loop_item_title',function(){
global $product;
echo wc_display_product_attributes( $product );
} );
此代码启用或显示所有属性,但我只需要显示特定属性。
您可以尝试使用 Woocommerce 的 get_product_attributes() 函数。这将返回一个产品属性数组,其中每个属性都是一个包含属性名称和值的对象。
add_action( 'woocommerce_shop_loop_item_title', 'display_custom_attribute' );
function display_custom_attribute() {
global $product;
// Getting all product attributes
$attributes = $product->get_attributes();
// confirming if the attribute you want to display exist
// don't forget to replace your custom attribute name
if ( isset( $attributes['your_custom_attribute_name'] ) ) {
// retrieving the attribute object
$attribute = $attributes['your_custom_attribute_name'];
// then retrieving the attribute name and value
$attribute_name = $attribute->get_name();
$attribute_value = $attribute->get_options()[0]; // This is assuming that the attribute has only one value
// finally echoing the attribute name and value
echo '<div class="custom-attribute">';
echo '<span class="attribute-name">' . $attribute_name . ': </span>';
echo '<span class="attribute-value">' . $attribute_value . '</span>';
echo '</div>';
}
}