WC_Product_Data_Store_CPT::create_all_product_variations( WC_Product $product, int $limit = -1 )

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


Description Description


Parameters Parameters

$product

(Required) Variable product.

$limit

(Optional) Limit the number of created variations.

Default value: -1


Top ↑

Return Return

(int) Number of created variations.


Top ↑

Source Source

File: includes/data-stores/class-wc-product-data-store-cpt.php

	public function create_all_product_variations( $product, $limit = -1 ) {
		$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_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;
	}

Top ↑

Changelog Changelog

Changelog
Version Description
3.6.0 Introduced.


Top ↑

User Contributed Notes User Contributed Notes

You must log in before being able to contribute a note or feedback.