在 Woocommerce 单品中添加带有销售日期和售价的自定义文本

问题描述 投票:0回答:1

我有这段代码,它在售价后面添加了一个文本,它在日志中生成一个错误,指出“做错了”,即使函数文件中没有 PHP 错误。

知道为什么会“抱怨”吗?这是代码:

add_filter( 'woocommerce_get_price_html', 'sale_dates_after_price', 100, 2 );
function sale_dates_after_price( $price, $product ) {
    $sales_price_from = get_post_meta( $product->id, '_sale_price_dates_from', true );
    $sales_price_to   = get_post_meta( $product->id, '_sale_price_dates_to', true );
    if ( is_single() && $product->is_on_sale() && $sales_price_to != "" ) {
        $sales_price_date_from = date( "j M y", $sales_price_from );
        $sales_price_date_to   = date( "j M y", $sales_price_to );
        $price = str_replace( '</ins>', ' </ins> <span class="sale-dates"><b>offer valid between ' . $sales_price_date_from . ' and ' . $sales_price_date_to . '</b></span>', $price );
    }
    return apply_filters( 'woocommerce_get_price', $price );
}
php wordpress woocommerce discount product-price
1个回答
1
投票

您的代码已经过时,存在一些错误和错误......当您使用格式化的销售价格时,有一个更好的钩子。尝试以下操作:

add_filter( 'woocommerce_format_sale_price', 'sale_dates_after_price', 10, 3 );
function sale_dates_after_price ( $price, $regular_price, $sale_price ) {
    global $product;

    if( ! is_a($product, 'WC_Product') ) 
        return $price;

    $date_from = $product->get_date_on_sale_from();
    $date_to   = $product->get_date_on_sale_to();

    if( is_product() && ! ( empty($date_from) && empty($date_to) ) ) {
        $date_from = date( "j M y", strtotime($date_from) );
        $date_to   = date( "j M y", strtotime($date_to) );
        $price    .= ' <span class="sale-dates"><strong>offer valid between '.$date_from.' and '.$date_to.'</strong></span>';
    }

    return $price;
}

代码位于活动子主题(或活动主题)的 function.php 文件中。已测试并有效。

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.