skip to Main Content

I’m writing a script for an e-commerce with Woocommerce who read a csv and set new price/sale price on product.
The variable below are an example.

With this code I’m able to set price and sale price on product, but when the sale data is expired, the price don’t return to regular price.

$price = '40';
$sale_price = array();
$sale_price[1] = '20';
$sale_price[2] = '2020-02-10';
$sale_price[3] = '2020-02-11';

update_post_meta( $product_id, '_price', $price );
update_post_meta( $product_id, '_regular_price', $price);

if( !empty($sale_price) ){
    update_post_meta( $product_id, '_price', $sale_price[1] );
    update_post_meta( $product_id, '_sale_price', $sale_price[1] );
    update_post_meta( $product_id, '_sale_price_dates_from', $sale_price[2] );
    update_post_meta( $product_id, '_sale_price_dates_to', $sale_price[3] );
}

if I don’t set the ‘_price’ post_meta I can’t see the regular price or the sale price.

3

Answers


  1. Please try below code that might help you

    $price = '40';
    $sale_price = array();
    $sale_price[1] = '20';
    $sale_price[2] = strtotime('2020-02-10');
    $sale_price[3] = strtotime('2020-02-11');
    
    update_post_meta( $product_id, '_price', $price );
    update_post_meta( $product_id, '_regular_price', $price);
    
    if( !empty($sale_price) ){
        update_post_meta( $product_id, '_price', $sale_price[1] );
        update_post_meta( $product_id, '_sale_price', $sale_price[1] );
        update_post_meta( $product_id, '_sale_price_dates_from', $sale_price[2] );
        update_post_meta( $product_id, '_sale_price_dates_to', $sale_price[3] );
    }
    
    Login or Signup to reply.
  2. You should do it this way:

    $product = wc_get_product($product_id);
    
    $price = '40';
    $sale_price = array();
    $sale_price[0] = '20';
    $sale_price[1] = date( 'Y-m-d 00:00:00', strtotime('2020-02-10'));
    $sale_price[2] = date( 'Y-m-d 23:59:59', strtotime('2020-02-11'));
    
    if ( !is_wp_error( $product ) ) {
        $product->set_price( $price );
        $product->set_regular_price( $price );
    
        if( !empty($sale_price) ){
            $product->set_price( $sale_price[0] );
            $product->set_sale_price( $sale_price[0] );
            $product->set_date_on_sale_from( $sale_price[1] );
            $product->set_date_on_sale_to( $sale_price[2] );
        }
    
        $product->save(); // save the product
    }
    
    Login or Signup to reply.
  3. The trick is to clear the transient cache.

    PUT /wp-json/wc/v3/system_status/tools/clear_transients

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