WC_Product_Data_Store_CPT::sort_all_product_variations()publicWC 1.0

Make sure all variations have a sort order set so they can be reordered correctly.

Method of the class: WC_Product_Data_Store_CPT{}

No Hooks.

Return

null. Nothing (null).

Usage

$WC_Product_Data_Store_CPT = new WC_Product_Data_Store_CPT();
$WC_Product_Data_Store_CPT->sort_all_product_variations( $parent_id );
$parent_id(int) (required)
Product ID.

WC_Product_Data_Store_CPT::sort_all_product_variations() code WC 9.4.2

public function sort_all_product_variations( $parent_id ) {
	global $wpdb;

	// phpcs:ignore WordPress.VIP.DirectDatabaseQuery.DirectQuery
	$ids   = $wpdb->get_col(
		$wpdb->prepare(
			"SELECT ID FROM {$wpdb->posts} WHERE post_type = 'product_variation' AND post_parent = %d AND post_status in ( 'publish', 'private' ) ORDER BY menu_order ASC, ID ASC",
			$parent_id
		)
	);
	$index = 1;

	foreach ( $ids as $id ) {
		// phpcs:ignore WordPress.VIP.DirectDatabaseQuery.DirectQuery
		$wpdb->update( $wpdb->posts, array( 'menu_order' => ( $index++ ) ), array( 'ID' => absint( $id ) ) );
	}
}