WC_Product_Variable_Data_Store_CPT::sync_price
Sync variable product prices with children.
Метод класса: WC_Product_Variable_Data_Store_CPT{}
Хуки из метода
Возвращает
null. Ничего (null).
Использование
$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) (обязательный) (передается по ссылке — &)
- Product object.
Список изменений
| С версии 3.0.0 | Введена. |
Код WC_Product_Variable_Data_Store_CPT::sync_price() WC Product Variable Data Store CPT::sync price WC 11.2.2
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();
// Performance note: prefilter with metadata_exists, to avoid unnecessary meta cache invalidations and SQLs.
$price_metas = array_filter(
array( '_price', '_sale_price', '_regular_price' ),
static fn( $meta_key ) => metadata_exists( 'post', $product_id, $meta_key )
);
array_walk( $price_metas, static fn( $meta_key ) => delete_post_meta( $product_id, $meta_key ) );
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 );
}