在单独的行中显示 woocommerce 产品尺寸

Display woocommerce product dimensions in separate lines

我通过将 product-attributes.php 文件复制到我的子主题并替换:

找到了在单独的行中显示尺寸的方法
<?php if ( $display_dimensions && $product->has_dimensions() ) : ?>
    <tr>
        <th><?php _e( 'Dimensions', 'woocommerce' ) ?></th>
        <td class="product_dimensions"><?php echo esc_html( wc_format_dimensions( $product->get_dimensions( false ) ) ); ?></td>
    </tr>
<?php endif; ?>

与:

<?php if ( $display_dimensions && $product->has_dimensions() ) : ?>
    <tr>
        <th>Length</th>
        <td class="product_dimensions"><?php echo $product->get_length() . get_option( 'woocommerce_dimension_unit' ); ?></td>
    </tr>
    <tr>
        <th>Width</th>
        <td class="product_dimensions"><?php echo $product->get_width() . get_option( 'woocommerce_dimension_unit' ); ?></td>
    </tr>
    <tr>
        <th>Height</th>
        <td class="product_dimensions"><?php echo $product->get_height() . get_option( 'woocommerce_dimension_unit' ); ?></td>
    </tr>
<?php endif; ?>

问题是产品并不总是具有 3 个维度... 然后它看起来像这样:

如何只显示相关行?

已更新: 您可以通过这种方式为每个维度类型添加条件:

<?php

    // For non variable products (separated dimensions)
    if ( $display_dimensions && $product->has_dimensions() && ! $product->is_type('variable') ) :
        if ( ! empty( $product->get_length() ) ) { ?>
    <tr>
        <th>Length</th>
        <td class="product_dimensions"><?php echo $product->get_length() . get_option( 'woocommerce_dimension_unit' ); ?></td>
    </tr>
<?php   }
        if ( ! empty( $product->get_width() ) ) { ?>
    <tr>
        <th>Width</th>
        <td class="product_dimensions"><?php echo $product->get_width() . get_option( 'woocommerce_dimension_unit' ); ?></td>
    </tr>
<?php   }
        if ( ! empty( $product->get_height() ) ) { ?>
    <tr>
        <th>Height</th>
        <td class="product_dimensions"><?php echo $product->get_height() . get_option( 'woocommerce_dimension_unit' ); ?></td>
    </tr>
<?php

    // For variable products (we keep the default formatted dimensions)
    elseif ( $display_dimensions && $product->has_dimensions() && $product->is_type('variable') ) : ?>
    <tr>
        <th><?php _e( 'Dimensions', 'woocommerce' ) ?></th>
        <td class="product_dimensions"><?php echo esc_html( wc_format_dimensions( $product->get_dimensions( false ) ) ); ?></td>
    </tr>
<?php endif; ?>

已测试并有效。

Note: This doesn't handle variable products that uses Javascript to update the formatted dimensions on selected product variations.