WC_Product_Data_Store_CPT::sort_all_product_variations │ public │ WC 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.

Returns

void. 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 11.1.2

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

	$index = 1;
	$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
		)
	);

	foreach ( $ids as $id ) {
		$product_id = absint( $id );
		$updated    = (bool) $wpdb->update( $wpdb->posts, array( 'menu_order' => ( $index++ ) ), array( 'ID' => $product_id ) );
		if ( $updated ) {
			clean_post_cache( $product_id );
		}
	}
}