Automattic\WooCommerce\Internal\CLI\Migrator\Core

WooCommerceProductImporter::get_or_create_termsprivateWC 1.0

Helper to get or create term IDs for a given taxonomy.

Method of the class: WooCommerceProductImporter{}

No Hooks.

Returns

Array. Array of term IDs.

Usage

// private - for code of main (parent) class only
$result = $this->get_or_create_terms( $terms_data, $taxonomy ): array;
$terms_data(array) (required)
Array of ['name' => ..., 'slug' => ...].
$taxonomy(string) (required)
Taxonomy slug.

WooCommerceProductImporter::get_or_create_terms() code WC 10.8.1

private function get_or_create_terms( array $terms_data, string $taxonomy ): array {
	$term_ids = array();
	foreach ( $terms_data as $term_info ) {
		$term_name = $term_info['name'] ?? null;
		$term_slug = $term_info['slug'] ?? sanitize_title( $term_name );

		if ( empty( $term_name ) || empty( $term_slug ) ) {
			continue;
		}

		$term = get_term_by( 'slug', $term_slug, $taxonomy );

		if ( ! $term ) {
			$term_result = wp_insert_term( $term_name, $taxonomy, array( 'slug' => $term_slug ) );
			if ( is_wp_error( $term_result ) ) {
				wc_get_logger()->warning( "Failed to insert term '{$term_name}' (slug: {$term_slug}) into {$taxonomy}: " . $term_result->get_error_message(), array( 'source' => 'wc-migrator' ) );
				continue;
			}
			$term_ids[] = $term_result['term_id'];
		} else {
			$term_ids[] = $term->term_id;
		}
	}
	return array_unique( $term_ids );
}