WC_Product_Variable_Data_Store_CPT::sync_pricepublicWC 3.0.0

Sync variable product prices with children.

Method of the class: WC_Product_Variable_Data_Store_CPT{}

Hooks from the method

Returns

null. Nothing (null).

Usage

$WC_Product_Variable_Data_Store_CPT = new WC_Product_Variable_Data_Store_CPT();
$WC_Product_Variable_Data_Store_CPT->sync_price( $product );
$product(WC_Product) (required) (passed by reference — &)
Product object.

Changelog

Since 3.0.0 Introduced.

WC_Product_Variable_Data_Store_CPT::sync_price() code WC 11.1.1

public function sync_price( &$product ) {
	global $wpdb;

	$prices    = array();
	$child_ids = $product->get_visible_children();
	if ( ! empty( $child_ids ) ) {
		$placeholders = implode( ', ', array_fill( 0, count( $child_ids ), '%d' ) );
		// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
		$prices = $wpdb->get_col(
			$wpdb->prepare(
				"SELECT DISTINCT meta_value FROM {$wpdb->postmeta} WHERE meta_key = '_price' AND post_id IN ( {$placeholders} )",
				$child_ids
			)
		);
		// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
	}

	$product_id = $product->get_id();

	delete_post_meta( $product_id, '_price' );
	delete_post_meta( $product_id, '_sale_price' );
	delete_post_meta( $product_id, '_regular_price' );

	if ( $prices ) {
		sort( $prices, SORT_NUMERIC );
		// To allow sorting and filtering by multiple values, we have no choice but to store child prices in this manner.
		foreach ( $prices as $price ) {
			if ( is_null( $price ) || '' === $price ) {
				continue;
			}
			add_post_meta( $product_id, '_price', $price, false );
		}
	}

	$this->update_lookup_table( $product_id, 'wc_product_meta_lookup' );

	/**
	 * Fire an action for this direct update so it can be detected by other code.
	 *
	 * @since 3.6
	 * @param int $product_id Product ID that was updated directly.
	 */
	do_action( 'woocommerce_updated_product_price', $product_id );
}