如何在WooCommerce文本输入框中正确显示格式化用户消费总额
解决WooCommerce输入框显示格式化价格时出现
<span>标签的问题 问题原因
wc_price()函数默认会返回包含<span>标签的HTML结构(例如:<span class="woocommerce-Price-amount amount"><bdi>€1,234.56</bdi></span>)。直接将这段HTML赋值给input的value属性时,浏览器会把标签文本显示在输入框内,实际价格则因标签闭合跑到输入框外。
解决方案
调用wc_price()时传入html => false的参数,让函数返回纯文本格式的格式化价格,不生成任何HTML标签。
修改后的短代码代码
add_shortcode('user_total_spent', 'get_user_total_spent'); function get_user_total_spent( $atts ) { extract( shortcode_atts( array( 'user_id' => get_current_user_id(), ), $atts, 'user_total_spent' ) ); if( $user_id > 0 ) { $customer = new WC_Customer( $user_id ); // 获取WC_Customer对象 $total_spent = $customer->get_total_spent(); // 获取用户累计消费金额 // 传入html参数为false,获取不带HTML标签的纯文本价格 return wc_price( $total_spent, array('html' => false) ); } }
原理说明
wc_price()的第二个参数是配置数组,其中html选项控制是否生成包裹价格的HTML标签:
- 默认为
true:返回带<span>的HTML结构 - 设置为
false:仅返回包含货币符号、正确小数分隔符的纯文本字符串(比如€1,234.56)
修改后,短代码返回的纯文本价格可直接赋值给input的value属性,输入框内会正常显示带格式的价格,不会出现任何标签。
输入框代码无需修改
你的输入框渲染代码保持原样即可,现在短代码返回的纯文本可直接插入value属性中:
add_action( 'woocommerce_account_informes_endpoint', 'ani_populate_informes_page' ); function ani_populate_informes_page() { $totalGasto = do_shortcode('[user_total_spent]'); echo ' <h3>Informes</h3> <p>Aquí puedes encontrar un informe del gasto que has realizado en nuestra tienda.</p> <div> <label for="gastototalclientemicuenta">Gasto total:</label> <input type="text" id="gastototalclientemicuenta" name="gastototalclientemicuenta" value="'. $totalGasto .'" readonly> <br> </div> '; }
内容的提问来源于stack exchange,提问作者Nerea
相关产品推荐
相关产品推荐

