Skip to content
Advertisement

Display woocommerce product dimensions in separate lines

I found the way to display the dimensions in separate lines by copy product-attributes.php file to my child-theme and replace:

<?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; ?>

with:

<?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; ?>

The problem is that the products don’t always have 3 dimensions… And then it look like this:

Screen Shot

How can I display only the relevant rows?

Advertisement

Answer

Updated: You can do it this way adding a condition for each dimension kind this way:

<?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; ?>

Tested and works.

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

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement