在 WooCommerce 格式的产品尺寸输出中将长度重命名为直径

Rename Length to Diameter in WooCommerce formatted product dimensions output

我正在使用这个 woocommerce_format_dimensions 过滤器挂钩来替换显示的尺寸格式,从 1 x 1 x 1 in1 长英寸 x 1 宽英寸 x 1 高英寸

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$dimensions 数组如下所示:

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

如何将 “长度” 键重命名为 “直径” 并将尺寸顺序更改为相反的顺序,以便最终结果将是:

1 高英寸 x 1 宽英寸 x 1 深英寸

我尝试使用 array_map 重命名 $dimensions 数组中的键,但无法成功正在工作。

2020 年更新

你只需要设置 array keys/values 就像你想要的那样(重命名一个键并重新排序你的数组),这样:

add_filter( 'woocommerce_format_dimensions', 'Custom_formated_product_dimentions_with_labels', 10, 2 );
function Custom_formated_product_dimentions_with_labels( $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 ) );

    $label_with_dimensions = array();

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

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

代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件。

此代码已在 WooCommerce 版本 3+ 上测试并有效