在Woocommerce中附加其他显示的尺寸和重量单位

问题描述 投票:2回答:1

有人可以共享功能代码,在Woocommerce中为当前单位旁边的另一个单位提供重量和尺寸吗?

像图像波纹管的例子

enter image description here

php wordpress woocommerce product dimensions
1个回答
4
投票

更新2(2019年3月)

根据需要,以下代码将附加到默认显示的尺寸和重量的其他转换单位值:

add_filter( 'woocommerce_format_weight', 'custom_format_weight', 20, 2 );
function custom_format_weight( $weight_string, $weight ){
    // Format decimals from default weight value
    $weight_string  = wc_format_localized_decimal( $weight );
    // Format decimals from custom converted weight value
    $weight_string2 = wc_format_localized_decimal( round($weight * 0.45359237, 2) );

    if ( ! empty( $weight_string ) ) {
        $weight_string2 = ' ( ' . $weight_string2 . ' ' . __( 'kg', 'woocommerce' ) . ' )';
        $weight_string .= ' ' . get_option( 'woocommerce_weight_unit' ) . $weight_string2;
    } else {
        $weight_string = __( 'N/A', 'woocommerce' );
    }

    return $weight_string;
}

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 ) . ' ' . __( 'cm', 'woocommerce' ) . ' )';
        $dimension_string .= ' ' . get_option( 'woocommerce_dimension_unit' ) . $dimension_string2;
    } else {
        $dimension_string = __( 'N/A', 'woocommerce' );
    }

    return $dimension_string;
}

代码位于活动子主题(或活动主题)的function.php文件中。测试和工作。

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.