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

标签 php wordpress woocommerce product dimensions

我正在使用此 woocommerce_format_dimensions 过滤器 Hook 将显示的尺寸格式从 1 x 1 x 1 英寸 替换为 1 L英寸 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);
}
$dimensions 数组的

var_dump 如下所示:

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

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

1 高 x 1 宽 x 1 深

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

最佳答案

2020 年更新

您只需设置数组 / 如您希望它们出现在您的函数中(重命名一个键并重新排序数组),这样:

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+ 上进行了测试并且有效

关于php - 在 WooCommerce 格式的产品尺寸输出中将长度重命名为直径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45401876/

相关文章:

php - 是否可以在一行中选择随机列?

PHP:特殊字符作为数组中的键

css - 在我的 Wordpress 网站上更改主导航菜单字体颜色

php - 在 Woocommerce 中显示总购物车运输量值

php - 检查用户/访客是否在 WooCommerce 中购买了特定产品

php - 从准备好的语句中获取数据

php - HTML 表单 - 阻止某些用户选中复选框

php - 父类别作为 wordpress 中的主菜单和子类别作为子菜单

wordpress - 如何从 WooCommerce 中删除结帐选项?

wordpress - Paypal 自适应支付插件不适用于 WooCommerce