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

Add custom text with sale dates after sale price in Woocommerce Single product

我有这段代码,它在促销价之后添加了一个文本,并且它在日志中生成了一条错误消息 "doing it wrong",即使函数文件中没有 PHP 错误。

知道为什么是 "complaining" 吗?这是代码:

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 );
}

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

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 文件。已测试并有效。