WooCommerce 自定义商品价格显示HTML结构

时间:2022-04-23
本文章向大家介绍WooCommerce 自定义商品价格显示HTML结构,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

WooCommerce 虽然有中文本地化支持,但整个插件本身是按照欧美人的习惯去开发的,一些细节上不可能做到各个国家或地区的用户满意。下面就用一个例子抛砖引玉,自定义商品价格显示HTML结构。

默认的话,WooCommerce 输出商品价格显示HTML结构是这样的(当商品本身设置了一般价格与优惠价):

<a href=""> <span class="onsale">促销中</span> <img src="xxxx.png"> <h3>商品名称</h3> <span class="price"><del><span class="amount">¥109.00</span></del> <ins><span class="amount">¥99.00</span></ins></span> </a>

前端显示的话类似:

新旧价格的显示大概遵循“¥109.00 ¥99.00”的形式,但根据国人的习惯(不知道是不是这样?),一般显示为 “¥99.00 ¥109.00 ”。要想显示出我们的效果的话,那就可以通过对woocommerce_get_price_html 函数下刀,hook之。

代码如下:

<?php // DeveWork.com //这是一个可以修改woocommerce_get_price_html 函数默认输出的html代码的例子, //作用是调换新旧价格的位置 //感谢http://wordpress.stackexchange.com/questions/83367/how-to-edit-the-get-price-html-on-woocommerce   add_filter( 'woocommerce_get_price_html', 'dw_change_default_price_html', 100, 2 );   function dw_change_default_price_html( $price,$product ){ if ( $product->price > 0 ) { if ( $product->price && isset( $product->regular_price ) ) { $from = $product->regular_price; $to = $product->price; return '<ins><span class="amount">'.( ( is_numeric( $to ) ) ? woocommerce_price( $to ) : $to ) .'</span></ins> <del><span class="amount">'. ( ( is_numeric( $from ) ) ? woocommerce_price( $from ) : $from ) .' </span></del>'; } else { $to = $product->price; return '<ins><span class="amount">' . ( ( is_numeric( $to ) ) ? woocommerce_price( $to ) : $to ) . '</span></ins>'; } } else { return '免费'; } } ?>

代码已经托管到 Github gist 上:https://gist.github.com/Jeff2Ma/91c6f19ab63552be269c