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

如何在PHP中将WooCommerce变体选项的价格文本移至下一行

解决WooCommerce变体下拉菜单价格换行问题

要让变体名称与价格分两行显示,只需在返回变体选项内容时插入换行标签,并确保HTML标签不被过滤,修改代码如下:

// Display the product variation price inside the variations dropdown.
add_filter( 'woocommerce_variation_option_name', 'display_price_in_variation_option_name' );
function display_price_in_variation_option_name( $term ) {
    global $wpdb, $product;

    if ( empty( $term ) || empty( $product->id ) ) {
        return $term;
    }

    $result    = $wpdb->get_col( "SELECT slug FROM {$wpdb->prefix}terms WHERE name = '$term'" );
    $term_slug = ! empty( $result ) ? $result[0] : $term;

    $query = "
        SELECT postmeta.post_id AS product_id
        FROM {$wpdb->prefix}postmeta AS postmeta
        LEFT JOIN {$wpdb->prefix}posts AS products ON ( products.ID = postmeta.post_id )
        WHERE postmeta.meta_key LIKE 'attribute_%'
        AND postmeta.meta_value = '$term_slug'
        AND products.post_parent = $product->id";

    $variation_id = $wpdb->get_col( $query );
    $parent       = wp_get_post_parent_id( $variation_id[0] ?? 0 );

    if ( $parent > 0 ) {
        $_product = new WC_Product_Variation( $variation_id[0] );
        // 插入<br>标签实现换行,同时允许wp_kses保留br标签
        return $term . '<br> - (' . wp_kses( woocommerce_price( $_product->get_price() ), array('br' => array()) ) . ' )';
    }

    return $term;
}

关键修改说明:

  1. 在变体名称与价格之间添加<br>标签,强制价格部分换行显示
  2. 更新wp_kses的允许标签列表,加入'br' => array(),避免换行标签被WordPress的HTML过滤机制移除
  3. 优化$variation_id[0]的取值逻辑,添加?? 0避免未找到变体时出现报错

如果需要调整换行后的价格样式,可添加自定义CSS:

select option br {
    display: block;
}
select option .price {
    padding-left: 10px;
    font-size: 0.9em;
    color: #666;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 03:25:36