Automattic\WooCommerce\Internal\CLI\Migrator\Core

WooCommerceProductImporter::set_product_taxonomiesprivateWC 1.0

Set product taxonomies (categories, tags, brand) before product save.

Method of the class: WooCommerceProductImporter{}

No Hooks.

Returns

null. Nothing (null).

Usage

// private - for code of main (parent) class only
$result = $this->set_product_taxonomies( $product, $product_data ): void;
$product(WC_Product) (required)
The product object.
$product_data(array) (required)
Standardized data containing taxonomies.

WooCommerceProductImporter::set_product_taxonomies() code WC 10.7.0

private function set_product_taxonomies( WC_Product $product, array $product_data ): void {
	$product_id = $product->get_id();
	if ( ! $product_id ) {
		$product_id = $product->save();
		if ( ! $product_id ) {
			wc_get_logger()->warning( 'Could not save product to set taxonomies.', array( 'source' => 'wc-migrator' ) );
			return;
		}
	}

	$taxonomies_to_set = array();

	if ( isset( $product_data['categories'] ) && is_array( $product_data['categories'] ) && $this->import_options['create_categories'] ) {
		$term_ids = $this->get_or_create_terms( $product_data['categories'], 'product_cat' );
		if ( ! empty( $term_ids ) ) {
			$taxonomies_to_set['product_cat'] = $term_ids;
		} elseif ( $this->import_options['assign_default_category'] ) {
			$default_cat_id = get_option( 'default_product_cat' );
			if ( $default_cat_id ) {
				$taxonomies_to_set['product_cat'] = array( $default_cat_id );
				wc_get_logger()->info( "Assigned default category (ID: {$default_cat_id}) to product with no categories", array( 'source' => 'wc-migrator' ) );
			}
		} else {
			wc_get_logger()->debug( 'Product has no categories and assign_default_category is disabled', array( 'source' => 'wc-migrator' ) );
		}
	}

	if ( isset( $product_data['tags'] ) && is_array( $product_data['tags'] ) && $this->import_options['create_tags'] ) {
		$term_ids = $this->get_or_create_terms( $product_data['tags'], 'product_tag' );
		if ( ! empty( $term_ids ) ) {
			$taxonomies_to_set['product_tag'] = $term_ids;
		}
	}

	if ( ! empty( $product_data['brand']['name'] ) && taxonomy_exists( 'product_brand' ) ) {
		$brand_data = array( $product_data['brand'] );
		$term_ids   = $this->get_or_create_terms( $brand_data, 'product_brand' );
		if ( ! empty( $term_ids ) ) {
			$taxonomies_to_set['product_brand'] = $term_ids;
		}
	}

	foreach ( $taxonomies_to_set as $taxonomy => $ids ) {
		wp_set_object_terms( $product_id, $ids, $taxonomy, false );
	}
}