I am displaying several product attributes and custom meta fields on the single product page with this code I got here:
function action_woocommerce_single_product_summary() {
global $product;
$attributes_names = array( 'Brand', 'Color', 'Size' );
$attributes_data = array();
foreach ( $attributes_names as $attribute_name ) {
if ( $value = $product->get_attribute($attribute_name) ) {
$attributes_data[] = $attribute_name . ': ' . $value;
}
}
// NOT empty
if ( ! empty($attributes_data) ) {
echo '<h4>' . __( 'Details', 'woocommerce' ) . '</h4><ul><li>' . implode( '</li><li>', $attributes_data );
}
// Get meta
$sn = $product->get_meta( 'Serial_Number' );
$mpn = $product->get_meta( 'MPN' );
// NOT empty
if ( ! empty ( $sn ) ) {
echo '<li>' . __( 'My label 1: ', 'woocommerce' ) . $sn . '</li>';
}
// NOT empty
if ( ! empty ( $mpn ) ) {
echo '<li>' . __( 'My label 2: ', 'woocommerce' ) . $mpn . '</li>';
}
echo '</ul>';
}
add_action( 'woocommerce_single_product_summary', 'action_woocommerce_single_product_summary', 36, 0 );
My problem is that the h4 ('Details') and the starting ul are only displayed when there are attributes. When there are only custom fields set for a product, the h4 and the starting ul for the list are not displayed. How can I always show the h4 and the starting
- whenever either an attribute or a custom field is set for a product?
- products that have attributes AND custom fields
- products that ONLY have an attribute OR custom field
- products that neither have an attribute or custom field
EDIT to clarify: There are 3 possible product types:
For the first type of products, it should be displayed for example:
<h4>Details</h4>
<ul>
<li>Brand: ...</li>
<li>MPN: ...</li>
</ul>
For the second type of products an example would be:
<h4>Details</h4>
<ul>
<li>MPN: ...</li>
</ul>
and for the last type of products NOTHING should be displayed at all.