'Woocommerce add labels to custom dimension unit on front end
Need to implement custom dimension labels for custom dimensions output on front end.
I have found codes below which work well on their own but not together, so trying to implement the two into 1 compatible code.
- code 1. Outputs woocommerce product dimensions on frontend in both units "CM" & "IN" x2 custom dimension units without custom labels
Code 1.
add_filter( 'woocommerce_format_dimensions', 'custom_format_dimensions', 10, 2 );
function custom_format_dimensions( $dimension_string, $dimensions ){
// Initializing variable
$dimentions2 = array();
// Loop though dimensions array (and set custom converted formatted decimals values in a new array)
foreach( $dimensions as $key => $value ){
if( ! empty($value) && $value != 0 )
$dimentions2[$key] = wc_format_localized_decimal( round($value * 2.54, 2) );
}
// Format default dimentions in a string
$dimension_string = implode( ' x ', array_filter( array_map( 'wc_format_localized_decimal', $dimensions ) ) );
if ( ! empty( $dimension_string ) ) {
// Format custom converted array in a string and append it to default formatted dimensions string
$dimension_string2 = ' ( ' . implode( ' x ', $dimentions2 ) . ' ' . __( 'in', 'woocommerce' ) . ' )';
$dimension_string .= ' ' . get_option( 'woocommerce_dimension_unit' ) . $dimension_string2;
} else {
$dimension_string = __( 'N/A', 'woocommerce' );
}
return $dimension_string;
}
- Code 2. Add custom labels to output dimensions. For example "D X W X H (cm)" & "D X W X H (in)" Woocommerce dimension units with custom labels
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' );
$dimensions = array_filter( array_map( 'wc_format_localized_decimal', $dimensions ) );
return 'D'.$dimensions['length'].' x W'.$dimensions['width'].' x H'.$dimensions['height'].' (cm)';
}
How to make code 1 output with code 2 labels? I have tried for many hours replacing dimensions array etc from one snippet to the other but no luck. Any help would be very much appreciated.
Admin feel free to edit!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
