WC_Product_CSV_Importer::parse_categories_field()publicWC 1.0

Parse a category field from a CSV. Categories are separated by commas and subcategories are "parent > subcategory".

Method of the class: WC_Product_CSV_Importer{}

No Hooks.

Return

Array. of arrays with "parent" and "name" keys.

Usage

$WC_Product_CSV_Importer = new WC_Product_CSV_Importer();
$WC_Product_CSV_Importer->parse_categories_field( $value );
$value(string) (required)
Field value.

WC_Product_CSV_Importer::parse_categories_field() code WC 9.4.2

public function parse_categories_field( $value ) {
	if ( empty( $value ) ) {
		return array();
	}

	$row_terms  = $this->explode_values( $value );
	$categories = array();

	foreach ( $row_terms as $row_term ) {
		$parent = null;
		$_terms = array_map( 'trim', explode( '>', $row_term ) );
		$total  = count( $_terms );

		foreach ( $_terms as $index => $_term ) {
			// Don't allow users without capabilities to create new categories.
			if ( ! current_user_can( 'manage_product_terms' ) ) {
				break;
			}

			$term = wp_insert_term( $_term, 'product_cat', array( 'parent' => intval( $parent ) ) );

			if ( is_wp_error( $term ) ) {
				if ( $term->get_error_code() === 'term_exists' ) {
					// When term exists, error data should contain existing term id.
					$term_id = $term->get_error_data();
				} else {
					break; // We cannot continue on any other error.
				}
			} else {
				// New term.
				$term_id = $term['term_id'];
			}

			// Only requires assign the last category.
			if ( ( 1 + $index ) === $total ) {
				$categories[] = $term_id;
			} else {
				// Store parent to be able to insert or query categories based in parent ID.
				$parent = $term_id;
			}
		}
	}

	return $categories;
}