首页 > 解决方案 > 如何修改 get_price_html 以为特价商品创建自定义价格显示

问题描述

这是我关于 Stack Overflow 的第一个问题……我正在为客户修改 WooCommerce 网站。他们想要的是所有具有销售价格的物品在销售价格旁边显示一个红点。我在 abstract-wc-product.php 中找到了公共函数“get_price_html”:

    /**
     * Returns the price in html format.
     *
     * @param string $deprecated Deprecated param.
     *
     * @return string
     */
    public function get_price_html( $deprecated = '' ) {
        if ( '' === $this->get_price() ) {
            $price = apply_filters( 'woocommerce_empty_price_html', '', $this );
        } elseif ( $this->is_on_sale() ) {
            $price = wc_format_sale_price( wc_get_price_to_display( $this, array( 'price' => $this->get_regular_price() ) ), wc_get_price_to_display( $this ) ) . $this->get_price_suffix();
        } else {
            $price = wc_price( wc_get_price_to_display( $this ) ) . $this->get_price_suffix();
        }

        return apply_filters( 'woocommerce_get_price_html', $price, $this );
    }

我发现如果我修改“elseif ($this->is_on_sale()”部分,我可以做我想做的事,而且这有效,但只有当我修改并上传 abstract-wc-product 的核心版本时。 php,我不想这样做。

我有子主题,在我的子主题目录中,我已将 abstract-wc-product.php 复制到以下文件夹结构中:

woocommerce/包括/摘要

这不起作用,所以我也尝试将上面的函数复制到我的 functions.php 文件中,看看这是否会覆盖核心版本。

这些都不起作用 - 任何人都可以帮助如何做到这一点,拜托?

谢谢!

斯图尔特

标签: wordpresswoocommerce

解决方案


如果你不能使用 CSS,你可以这样做:

/* Here's the woocommerce filter. Then we use a static function (anonymous function) to pass the two arguments that the original filter passes.*/
add_filter( 'woocommerce_get_price_html', static function( $price, $product ) {
    // Now we check to see if the product is onsale.
    if ( $product->is_on_sale() ) :
        // Change this to whatever worked for you when you modified core files.
        $price = wc_format_sale_price( wc_get_price_to_display( $product, array( 'price' => $product->get_regular_price() ) ), wc_get_price_to_display( $product ) ) . $product->get_price_suffix();
    endif;

// Return the $price. This is here in the event the product that is passed isn't on sale. 
return $price;

}, 10, 2 );

这进入您的孩子主题functions.php


推荐阅读