skip to Main Content

I am trying programmatically set a sale start date.
I am using:


function mysalesdates( $product, $sale_start,$sale_end ) { 
  if ( ! is_a( $product, 'WC_Product' ) ) {
    $product = wc_get_product( $product );
  }

  if ( ! $product ) {
    return false;
  }
    $product->set_date_on_sale_from( $sale_start);
    $product->set_date_on_sale_to( $sale_end );
    $product->save();
 
    return;
  }

  $sale_start=strtotime("01 Jul 2024"); 
  $sale_end =strtotime("31 July 2024");
// I already have the product id stored in $myproduct_id from another function
  $product_saledates = mysalesdates($myproduct_id,$sale_start,$sale_end);

And I can verify that it adds the date to the _postmeta database and the sale start date shows as 2024-07-01 in Sale price dates when I edit the product.

The problem is that the although the product shows as ‘on sale’, there is the ON SALE badge over the product image. The product is showing the regular price and not the sale price. eg it shows Original price was: £15.71.Current price is: £15.71. inc VAT and does not show the sale price in the database.

If I edit the product and change nothing but simply save it then it works.

is there something that I need to call programmatically that does something that saving a product does to make this work.
Ican programmatically change prices, changes stock levels etc but for some reason woo does not act on the sale start date unless I then manually save the product,
Thanks
Steve

2

Answers


  1. Chosen as BEST ANSWER

    The Revised code I posted is working , Thanks to LoicTheAztec's for pointing me in the right direction.

    The strange this is that is Woocommerce did not show the sale prices instantly so there must be some caching going on. I still had the issue of all the right prices and dates in database but woocommerce was not showing the sales prices, but it has sorted itself overnight without me doing anything further.


  2. There are some mistakes in your code and there is no function or method that set or update the "sale price date from".

    From an existing WC_Product object, you need to use set_date_on_sale_from() method like:

    $date_from = strtotime('01 Jul 2024');
    
    $product->set_date_on_sale_from( $date_from );
    $product->save();
    

    Now it should work.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search