如何在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; }
关键修改说明:
- 在变体名称与价格之间添加
<br>标签,强制价格部分换行显示 - 更新
wp_kses的允许标签列表,加入'br' => array(),避免换行标签被WordPress的HTML过滤机制移除 - 优化
$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
相关产品推荐
相关产品推荐

