@@ -133,6 +133,11 @@ public static function batch( $amount, array $args = array() ) {
133133 return $ amount ;
134134 }
135135
136+ $ use_existing_terms = ! empty ( $ args ['use-existing-terms ' ] );
137+ if ( ! $ use_existing_terms ) {
138+ self ::maybe_generate_terms ( $ amount );
139+ }
140+
136141 $ product_ids = array ();
137142
138143 for ( $ i = 1 ; $ i <= $ amount ; $ i ++ ) {
@@ -419,6 +424,41 @@ protected static function generate_simple_product() {
419424 return $ product ;
420425 }
421426
427+ /**
428+ * Maybe generate a number of terms for use with products, if there aren't enough existing terms.
429+ *
430+ * Number of terms is determined by the number of products that will be generated.
431+ *
432+ * @param int $product_amount The number of products that will be generated.
433+ *
434+ * @return void
435+ */
436+ protected static function maybe_generate_terms ( int $ product_amount ): void {
437+ if ( $ product_amount < 10 ) {
438+ $ cats = 5 ;
439+ $ cat_depth = 1 ;
440+ $ tags = 10 ;
441+ } elseif ( $ product_amount < 50 ) {
442+ $ cats = 10 ;
443+ $ cat_depth = 2 ;
444+ $ tags = 20 ;
445+ } else {
446+ $ cats = 20 ;
447+ $ cat_depth = 3 ;
448+ $ tags = 40 ;
449+ }
450+
451+ $ existing_cats = count ( self ::get_term_ids ( 'product_cat ' , $ cats ) );
452+ if ( $ existing_cats < $ cats ) {
453+ Term::batch ( $ cats - $ existing_cats , 'product_cat ' , array ( 'max-depth ' => $ cat_depth ) );
454+ }
455+
456+ $ existing_tags = count ( self ::get_term_ids ( 'product_tag ' , $ tags ) );
457+ if ( $ existing_tags < $ tags ) {
458+ Term::batch ( $ tags - $ existing_tags , 'product_tag ' );
459+ }
460+ }
461+
422462 /**
423463 * Get a number of random term IDs for a specific taxonomy.
424464 *
@@ -427,7 +467,7 @@ protected static function generate_simple_product() {
427467 *
428468 * @return array
429469 */
430- protected static function get_term_ids ( $ taxonomy , $ limit ) {
470+ protected static function get_term_ids ( string $ taxonomy , int $ limit ): array {
431471 if ( $ limit <= 0 ) {
432472 return array ();
433473 }
0 commit comments