dswong
dswong

Reputation: 525

Reorder and customize product dimensions formatted output in WooCommerce

First of all, I would like to thank LoicTheAztec for the answer here. I'm looking for the very similar customization, but not 100% the same, what I want to achieve is: WxLxHmm

Yes, with the unit of measurement at the end.

Example : 200x600x200mm

With the answer provided, I managed to get 200mmx600mmx200mm

What to do if I would like to have the unit "mm" at the end only?

Below is my version of edited code

add_filter( 'woocommerce_format_dimensions', 'custom_formated_product_dimensions', 10, 2 );
function custom_formated_product_dimensions( $dimension_string, $dimensions ){
if ( empty( $dimension_string ) )
return __( 'N/A', 'woocommerce' );

// Set here your new array of dimensions based on existing keys/values
$new_dimensions = array( 
'width'  => $dimensions['width'],
'length' => $dimensions['length'],
'height' => $dimensions['height']
);
$dimensions = array_filter( array_map( 'wc_format_localized_decimal', $new_dimensions ) );

foreach( $dimensions as $key => $dimension ){
$label_with_dimensions[$key] = $dimension . '' . get_option( 'woocommerce_dimension_unit' ). '';
}

return implode( 'x',  $label_with_dimensions);
}

Upvotes: 1

Views: 566

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253886

To re-order dimensions output in a different way customization on your code that you need is:

add_filter( 'woocommerce_format_dimensions', 'custom_formated_product_dimentions', 10, 2 );
function custom_formated_product_dimentions( $dimension_string, $dimensions ){
    if ( empty( $dimension_string ) )
        return __( 'N/A', 'woocommerce' );

    // Set here your new reordered array of dimensions based on existing keys/values
    $new_dimentions = array(
        'width'  => $dimensions['width'],
        'length' => $dimensions['length'],
        'height' => $dimensions['height']
    );

    $dimensions = array_filter( array_map( 'wc_format_localized_decimal', $new_dimentions ) );

    return implode( 'x',  $dimensions) . get_option( 'woocommerce_dimension_unit' );
}

Code goes in function.php file of the active child theme (or active theme).

Tested and works.

This will output something like 200x600x200mm (with mm at the end just once).

Upvotes: 2

Related Questions