【问题标题】:How to override Woocommerce wc_format_sale_price function properly?如何正确覆盖 Woocommerce wc_format_sale_price 功能?
【发布时间】:2017-09-18 14:47:09
【问题描述】:

我正在努力完成这项任务,我真的需要一些帮助。首先,在有人将此标记为离题之前,我已经阅读了这里和其他网站的所有问题和答案。没有运气。

我正在尝试编辑位于 wc-formatting-functions.php 中的 wc_format_sale_price 函数的 HTML 输出。

原代码为:

function wc_format_sale_price( $regular_price, $sale_price ) {
$price = '<del>' . ( is_numeric( $regular_price ) ? wc_price( $regular_price ) : $regular_price ) . '</del> <ins>' . ( is_numeric( $sale_price ) ? wc_price( $sale_price ) : $sale_price ) . '</ins>';
return apply_filters( 'woocommerce_format_sale_price', $price, $regular_price, $sale_price );

如您所见,价格封装在 HTML 元素 &lt;del&gt;&lt;ins&gt; 中。

我确实尝试过直接更改 HTML 并且效果很好。

function wc_format_sale_price( $regular_price, $sale_price ) {
$price = '<div id="priceBefore" style="font-size: 16px;" class="old-price">' . ( is_numeric( $regular_price ) ? wc_price( $regular_price ) : $regular_price ) . '</div> <div id="priceAfter" style="font-size: 24px;" class="price">' . ( is_numeric( $sale_price ) ? wc_price( $sale_price ) : $sale_price ) . '</div>';
return apply_filters( 'woocommerce_format_sale_price', $price, $regular_price, $sale_price );

问题是我不想更改 WC 核心文件,因为这是一种不好的做法,并且每次店主更新 WC 插件时都会删除更改。 经过一番研究,我确信这应该在我的主题的 functions.php 文件中使用过滤器来完成,但所有关于此功能的教程和文章都非常混乱。我确实尝试过关注其中的几个,但结果却是空白页、重复的价格和类似的东西。

我知道过滤器和操作是 Wordpress/Woocommerce 主题开发的 alpha 和 omega,但我试图让它们发挥作用的尝试都失败了。

【问题讨论】:

    标签: woocommerce


    【解决方案1】:

    我实际上发现了如何解决这个问题。 我做了一些更多的研究,并在 Stack Overflow 上找到了这个答案:https://stackoverflow.com/a/45112008/6361752 其中名为 LoicTheAztec 的用户指出 woocommerce_format_sale_price 钩子接受三个参数。所以我添加了 $price 作为我的过滤器函数的第三个参数,现在它可以工作了。

    我放入主题的 functions.php 文件中的最终解决方案如下所示:

    add_filter('woocommerce_format_sale_price', 'ss_format_sale_price', 100, 3);
    function ss_format_sale_price( $price, $regular_price, $sale_price ) {
        $output_ss_price = '<div id="priceBefore" style="font-size: 16px;" class="old-price">' . ( is_numeric( $regular_price ) ? wc_price( $regular_price ) : $regular_price ) . '</div> <div id="priceAfter" style="font-size: 24px;" class="price">' . ( is_numeric( $sale_price ) ? wc_price( $sale_price ) : $sale_price ) . '</div>';
        return $output_ss_price;
    }
    

    我发布这个答案只是为了确保不再浪费时间在这么简单的事情上。

    我只想知道一件事。当我的过滤器函数需要接受三个参数才能正常工作时,原始函数怎么可能只使用两个参数并完美地工作?有什么想法吗?

    【讨论】:

    • 这个钩子的源代码是here ...是的,这个过滤器钩子中有3个参数可用。 $price 参数被定义到函数 wc_format_sale_price() 中,就在过滤器钩子之前……这就是为什么……
    猜你喜欢
    • 2016-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    • 2015-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多