You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WooCommerce商品价格的小数部分下方显示计量单位

解决方案

方案1:纯CSS实现(优先推荐,无需修改PHP代码)

直接在主题自定义CSS面板添加以下代码即可实现效果,不会影响后续主题、插件升级,你可以根据自己的字体大小微调参数适配:

/* 价格容器设为相对定位,作为单位的定位基准 */
.price .woocommerce-Price-amount {
  position: relative;
  display: inline-block;
  line-height: 1;
}
/* 调整小数上标和整数的间距 */
.price .woocommerce-Price-amount sup {
  margin-left: 2px;
  font-size: 0.75em;
}
/* 单位绝对定位到小数正下方 */
.price .uom {
  position: absolute;
  right: 0;
  bottom: -1em;
  font-size: 0.7em;
  white-space: nowrap;
}

方案2:修改PHP结构实现(兼容性更强)

如果不想使用CSS定位的方式,可以调整单位的插入位置,把单位和小数放在同一容器内实现上下排列,需要修改两处代码:

  1. 先修改functions.php中的小数拆分代码,新增容器包裹小数部分:
add_filter( 'formatted_woocommerce_price', 'ts_woo_decimal_price', 10, 5 );
function ts_woo_decimal_price( $formatted_price, $price, $decimal_places, $decimal_separator, $thousand_separator ) {
    $unit = number_format( intval( $price ), 0, $decimal_separator, $thousand_separator );
    $decimal = sprintf( '%02d', ( $price - intval( $price ) ) * 100 );
    // 新增容器包裹小数,后续单位会插入到这个容器内
    return $unit . '<span class="decimal-wrapper"><sup>' . $decimal . '</sup></span>';
}
  1. 修改WooCommerce Unit Of Measure插件的单位输出代码,把单位插入到小数容器内,而非整个价格末尾:
public function wc_uom_render_output( $price ) {
        global $post;
        $woo_uom_output = get_post_meta( $post->ID, '_woo_uom_input', true );
        if ( $woo_uom_output ) :
            $uom_html = '<span class="uom">' . esc_attr( $woo_uom_output, 'woocommerce-uom' ) . '</span>';
            // 替换字符串把单位插入到小数容器末尾
            $price = str_replace( '</span></bdi>', $uom_html . '</span></bdi>', $price );
            return $price;
        else :
            return $price;
        endif;
    }

最后添加少量CSS控制小数和单位上下排列:

.decimal-wrapper {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
  margin-left: 2px;
  font-size: 0.75em;
  line-height: 1.2;
}
.decimal-wrapper sup {
  position: static;
  font-size: 1em;
}

注意:直接修改插件源码会在插件升级后被覆盖,建议通过移除插件原有钩子、新增自定义钩子的方式实现修改,避免代码丢失。

内容的提问来源于stack exchange,提问作者namari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 14:15:09