WC_Product_Data_Store_CPT::create_all_product_variations()publicWC 3.6.0

Creates all possible combinations of variations from the attributes, without creating duplicates.

Method of the class: WC_Product_Data_Store_CPT{}

Hooks from the method

Return

Int. Number of created variations.

Usage

$WC_Product_Data_Store_CPT = new WC_Product_Data_Store_CPT();
$WC_Product_Data_Store_CPT->create_all_product_variations( $product, $limit, $default_values, $metadata );
$product(WC_Product) (required)
Variable product.
$limit(int)
Limit the number of created variations.
Default: -1
$default_values(array)
Key value pairs to set on created variations.
Default: array()
$metadata(array)
Key value pairs to set as meta data on created variations.
Default: array()

Changelog

Since 3.6.0 Introduced.

WC_Product_Data_Store_CPT::create_all_product_variations() code WC 9.4.2

public function create_all_product_variations( $product, $limit = -1, $default_values = array(), $metadata = array() ) {
	$count = 0;

	if ( ! $product ) {
		return $count;
	}

	$attributes = wc_list_pluck( array_filter( $product->get_attributes(), 'wc_attributes_array_filter_variation' ), 'get_slugs' );

	if ( empty( $attributes ) ) {
		return $count;
	}

	// Get existing variations so we don't create duplicates.
	$existing_variations = array_map( 'wc_get_product', $product->get_children() );
	$existing_attributes = array();

	foreach ( $existing_variations as $existing_variation ) {
		$existing_attributes[] = $existing_variation->get_attributes();
	}

	$possible_attributes = array_reverse( wc_array_cartesian( $attributes ) );

	foreach ( $possible_attributes as $possible_attribute ) {
		// Allow any order if key/values -- do not use strict mode.
		if ( in_array( $possible_attribute, $existing_attributes ) ) { // phpcs:ignore WordPress.PHP.StrictInArray.MissingTrueStrict
			continue;
		}
		$variation = wc_get_product_object( 'variation' );
		$variation->set_props( $default_values );
		foreach ( $metadata as $meta ) {
			$variation->add_meta_data( $meta['key'], $meta['value'] );
		}
		$variation->set_parent_id( $product->get_id() );
		$variation->set_attributes( $possible_attribute );
		$variation_id = $variation->save();

		do_action( 'product_variation_linked', $variation_id );

		++$count;

		if ( $limit > 0 && $count >= $limit ) {
			break;
		}
	}

	return $count;
}