Marco Marco - 3 months ago 20
PHP Question

Change the Product dimensions order in WooCommerce single product pages

I'm looking for a way to filter the display order or woocommerce product dimensions (Length, width, height). I'd like to display the height before the width.

At present I use a custom funtion to filter where the dimensions are displayed:

function wsa_show_product_dimensions() {
global $product;
echo $product->list_attributes();
}

add_action( 'woocommerce_single_product_summary', 'wsa_show_product_dimensions', 25 );


I've modified the product-attributes.php template in order to format the html that's returned:

<?php if ( $display_dimensions && $product->has_dimensions() ) : ?>
<div class="c-details-row">
<div class="c-details-col c-details-col_1">
<span class="c-label-middle"><?php _e( 'Size', 'woocommerce' ) ?></span>
</div>
<div class="c-details-col c-details-col_2">
<span class="c-label-middle"><?php echo esc_html( wc_format_dimensions( $product->get_dimensions( false ) ) ); ?></span>
</div>
</div>
<?php endif; ?>


I can see that I need to filter the
get_dimensions();
function but do not know how to re-order the array?

I see that
list_attributes();
is deprecated so any help on how to do this - using the new
wc_display_product_attributes
method if possible would be great.

Answer Source

First, since WooCommerce 3 WC_Product list_attributes() method is deprecated and it's replaced by wc_display_product_attributes( $product ).

To change the product dimensions order, you will need first to make your own function:

function get_product_dimensions_custom(){
    global $product;

    return  wc_format_dimensions( array(
        'length' => $product->get_length(),
        'height' => $product->get_height(),
        'width'  => $product->get_width(),
    ));
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Then You can use it in the template customization:

<?php if ( $display_dimensions && $product->has_dimensions() ) : ?>
    <div class="c-details-row">
        <div class="c-details-col c-details-col_1">
          <span class="c-label-middle"><?php _e( 'Size', 'woocommerce' ) ?></span>
        </div>
        <div class="c-details-col c-details-col_2">
          <span class="c-label-middle"><?php echo esc_html( get_product_dimensions_custom() ); ?></span>
        </div>
    </div>
<?php endif; ?>

To finish your custom hooked function in woocommerce_single_product_summary will be:

add_action( 'woocommerce_single_product_summary', 'wsa_show_product_dimensions', 25 );
function wsa_show_product_dimensions() {
    global $product;

    echo wc_display_product_attributes( $product );

}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested on WooCommerce 3+ and works;