WooCommerce 6.7变体旁显示价格:自定义价格格式问题
自定义WooCommerce变体选项旁的价格格式
直接修改现有代码中返回价格的部分即可,无需添加额外包装类或调整循环结构,具体操作如下:
修改步骤
- 定位原代码中两处返回变体名称+价格的代码行:
return $term_name . ' - (' . $product_price . ')'; - 将其替换为你需要的格式,直接拼接孟加拉塔卡符号与价格数值:
// 保留两位小数(可根据需求调整小数位数) $formatted_price = number_format($variation['display_price'], 2); return $term_name . ' - ( ৳ ' . $formatted_price . ' )';
修改后的完整代码
// Add the prices next to the variations in WooCommerce add_filter( 'woocommerce_variation_option_name', 'display_price_in_variation_option_names' ); function display_price_in_variation_option_names( $term_name ) { global $wpdb, $product; if ( is_product() && $product instanceof WC_Product && $product->is_type( 'variable' ) ) { foreach ( $product->get_available_variations() as $variation ) { foreach ( $variation['attributes'] as $variation_attribute_name => $variation_attribute_value ) { $result = $wpdb->get_col( "SELECT slug FROM {$wpdb->prefix}terms WHERE slug = '$variation_attribute_value'" ); $taxonomy = str_replace( 'attribute_', '', $variation_attribute_name ); $term = get_term_by( 'slug', $variation_attribute_value, $taxonomy ); if ( $term_name == $variation_attribute_value ) { // 自定义价格格式:保留两位小数,拼接孟加拉塔卡符号 $formatted_price = number_format($variation['display_price'], 2); return $term_name . ' - ( ৳ ' . $formatted_price . ' )'; } else if( is_object($term) && $term->name == $term_name ) { // 自定义价格格式:保留两位小数,拼接孟加拉塔卡符号 $formatted_price = number_format($variation['display_price'], 2); return $term_name . ' - ( ৳ ' . $formatted_price . ' )'; } } } } return $term_name; }
补充说明
- 直接调用
$variation['display_price']获取变体价格,避免wc_price生成的默认格式干扰 number_format函数用于控制价格小数位数,示例中保留2位,可根据需求修改参数- 完全沿用原有代码的循环与判断逻辑,无需额外添加包装类或ID
内容的提问来源于stack exchange,提问作者Saiful Islam
相关产品推荐
相关产品推荐

