Skip to content
Advertisement

Get on sale dates for the variations of a WooCommerce variable product

Is there any way to get on_sale_from and on_sale_to dates for WooCommerce variable products in an array using PHP?

The highlighted red boxes in this screenshot:

the red parts in this picture

Advertisement

Answer

Use the following to get the variations on_sale_from and on_sale_to dates for a variable product:

$sale_dates = array(); // Initializing

if( $product->is_type('variable') ) {
    $variation_ids = $product->get_visible_children();
    foreach( $variation_ids as $variation_id ) {
        $variation = wc_get_product( $variation_id );

        if ( $variation->is_on_sale() ) {
            $date_on_sale_from = $variation->get_date_on_sale_from();
            $date_on_sale_to   = $variation->get_date_on_sale_to();
            
            if( ! empty($date_on_sale_from) || ! empty($date_on_sale_to) ) {
                $sale_dates[$variation_id] = array(
                    'from' => $date_on_sale_from,
                    'to'   => $date_on_sale_to,
                );
            }
        }
    }
    
    // Array row output
    print_r($sale_dates);
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement