wc_apply_sale_state_for_product()WC 10.5.0

Apply the expected sale state for a product.

This is a shared helper used by both the per-product Action Scheduler callbacks and the daily cron safety net.

No Hooks.

Returns

null. Nothing (null).

Usage

wc_apply_sale_state_for_product( $product, $mode ): void;
$product(WC_Product) (required)
Product object.
$mode(string) (required)
'start' or 'end'.

Changelog

Since 10.5.0 Introduced.

wc_apply_sale_state_for_product() code WC 10.7.0

function wc_apply_sale_state_for_product( WC_Product $product, string $mode ): void {
	$product_id = $product->get_id();

	if ( 'start' === $mode ) {
		$sale_price = $product->get_sale_price( 'edit' );
		if ( $sale_price ) {
			$product->set_price( $sale_price );
			$product->save();

			// Workaround: `_price` is not in `meta_key_to_props` mapping and only syncs
			// when date/price props change in `handle_updated_props()`. Since we only
			// changed `price` prop, we must update `_price` meta directly.
			// See comment in `WC_Product_Data_Store_CPT::handle_updated_props()`.
			update_post_meta( $product_id, '_price', $sale_price );
		}
	} elseif ( 'end' === $mode ) {
		$regular_price = $product->get_regular_price( 'edit' );
		$product->set_price( $regular_price );

		$product->save();

		// Workaround: see above.
		update_post_meta( $product_id, '_price', $regular_price );
	}

	wc_delete_product_transients( $product_id );

	// Sync parent variable product price range if this is a variation.
	if ( $product->is_type( 'variation' ) ) {
		$parent_id = $product->get_parent_id();
		if ( $parent_id ) {
			WC_Product_Variable::sync( $parent_id );
		}
	}
}