Rename Length to Diameter in WooCommerce formatted

2019-06-04 19:31发布

I’m using this woocommerce_format_dimensions filter hook to replace displayed dimensions format from 1 x 1 x 1 in to 1 L in. x 1 W in. x 1 H in.

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' );

    $dimensions = array_filter( array_map( 'wc_format_localized_decimal', $dimensions ) );
    foreach( $dimensions as $key => $dimention )
        $label_with_dimensions[$key] = $dimention . ' ' . strtoupper( substr($key, 0, 1) ) . ' ' . get_option( 'woocommerce_dimension_unit' ) . '.';

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

var_dump of $dimensions array looks like this:

array(3) { ["length"]=> string(3) "104" ["width"]=> string(3) "136" ["height"]=> string(2) "53" }

How could I rename “length” key to “diameter” and change the order of dimensions to be in reverse, so that final result would be:

1 H in. x 1 W in. x 1 D in.

I have tried to rename keys in $dimensions array using array_map, but couldn't manage to get it working.

1条回答
甜甜的少女心
2楼-- · 2019-06-04 20:04

You just need to set the array keys/values as you want them in your function (renaming one key and reordering your array), this way:

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 array of dimensions based on existing keys/values
    $new_dimentions = array( 
        'height' => $dimensions['height'],
        'width'  => $dimensions['width'],
        'diameter' => $dimensions['length']
    );

    $dimensions = array_filter( array_map( 'wc_format_localized_decimal', $new_dimentions ) );
    foreach( $dimensions as $key => $dimention ){
        $label_with_dimensions[$key] = $dimention . ' ' . strtoupper( substr($key, 0, 1) ) . ' ' . get_option( 'woocommerce_dimension_unit' ) . '.';
    }

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

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 versions 3+ and works

查看更多
登录 后发表回答