batch, 'terms', 0 ); $made = 0; $slug = Marker::slug( $ctx->batch ); /* translators: %s: batch label. */ $parent = self::term( sprintf( __( 'Test data – %s', 'admin-powerups-for-woocommerce' ), $ctx->label ), $slug, 0, $ctx, $made ); $names = $ctx->words['categories']; $picked = array(); for ( $i = 0; $i < self::CHILDREN && $names; $i++ ) { $name = (string) $random->pick( $names ); $names = array_values( array_diff( $names, array( $name ) ) ); $picked[] = $name; } $children = array(); if ( $parent ) { foreach ( $picked as $i => $name ) { $id = self::term( $name, $slug . '-' . ( $i + 1 ), $parent, $ctx, $made ); if ( $id ) { $children[] = $id; } } } return array( 'parent' => $parent, 'children' => $children ? $children : ( $parent ? array( $parent ) : array() ), 'made' => $made, ); } /** * `created_term` (only inside our wp_insert_term()): the marker, in the same call. * * @since 1.0.0 * @param mixed $term_id Term ID. * @param mixed $tt_id Term taxonomy ID. * @param mixed $taxonomy Taxonomy. * @return void */ public static function mark( $term_id, $tt_id = 0, $taxonomy = '' ): void { if ( 'product_cat' === $taxonomy && '' !== self::$batch ) { update_term_meta( (int) $term_id, Marker::META, self::$batch ); } } /** * Insert one category, or reuse ours with that slug. * * @param string $name Name. * @param string $slug Slug. * @param int $parent_id Parent term ID. * @param Context $ctx Context. * @param int $made Counter. * @return int Term ID, 0 on failure. */ private static function term( string $name, string $slug, int $parent_id, Context $ctx, int &$made ): int { $batch = $ctx->batch; $existing = get_term_by( 'slug', $slug, 'product_cat' ); if ( $existing instanceof \WP_Term ) { $id = (int) $existing->term_id; $marker = (string) get_term_meta( $id, Marker::META, true ); if ( '' !== $marker && $batch !== $marker ) { return 0; } // The slug carries the batch's secret token: ours, from a step that died part-way. if ( ! Marker::verified( 'term', $id, $batch ) ) { update_term_meta( $id, Marker::META, $batch ); Marker::sign( 'term', $id, $batch ); } return $id; } self::$batch = $batch; add_action( 'created_term', array( __CLASS__, 'mark' ), 1, 3 ); try { $args = array( 'slug' => $slug, 'parent' => $parent_id, ); $result = wp_insert_term( $name, 'product_cat', $args ); if ( is_wp_error( $result ) && 'term_exists' === $result->get_error_code() ) { // Same name at this level (another batch with the same label): add the batch's token. $result = wp_insert_term( $name . ' (' . Marker::public_token( $batch ) . ')', 'product_cat', $args ); } } finally { remove_action( 'created_term', array( __CLASS__, 'mark' ), 1 ); self::$batch = ''; } if ( is_wp_error( $result ) ) { return 0; } $id = (int) $result['term_id']; Marker::sign( 'term', $id, $batch ); ++$made; $ctx->created( 'term', $id ); return $id; } }