user10551357
user10551357

Reputation:

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

I have this code which adds a text after the sale price and it's generating an error in the log saying "doing it wrong" even though there is no PHP error in the functions file.

Any idea why it's "complaining" ? Here's the code:

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

Upvotes: 1

Views: 1098

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 254493

Your code is outdated with some errors and mistakes… As you are using the formatted sale price, there is a much better hook for that. Try the following:

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

Code goes in function.php file of your active child theme (or active theme). Tested and works.

enter image description here

Upvotes: 1

Related Questions