WC_Brands_Admin::parse_brands_field
Parse brands field from a CSV during import.
Based on WC_Product_CSV_Importer::parse_categories_field()
Method of the class: WC_Brands_Admin{}
No Hooks.
Returns
Array.
Usage
$WC_Brands_Admin = new WC_Brands_Admin(); $WC_Brands_Admin->parse_brands_field( $value );
- $value(string) (required)
- Field value.
WC_Brands_Admin::parse_brands_field() WC Brands Admin::parse brands field code WC 10.5.0
public function parse_brands_field( $value ) {
if ( empty( $value ) ) {
return array();
}
// Based on WC_Product_Importer::explode_values().
$values = str_replace( '\\,', '::separator::', explode( ',', $value ) );
$row_terms = array();
foreach ( $values as $row_value ) {
$row_terms[] = trim( str_replace( '::separator::', ',', $row_value ) );
}
$brands = 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 brands.
if ( ! current_user_can( 'manage_product_terms' ) ) {
break;
}
$term = term_exists( $_term, 'product_brand', $parent );
if ( is_array( $term ) ) {
$term_id = $term['term_id'];
} else {
$term = wp_insert_term( $_term, 'product_brand', array( 'parent' => intval( $parent ) ) );
if ( is_wp_error( $term ) ) {
break; // We cannot continue if the term cannot be inserted.
}
$term_id = $term['term_id'];
}
// Only requires assign the last category.
if ( ( 1 + $index ) === $total ) {
$brands[] = $term_id;
} else {
// Store parent to be able to insert or query brands based in parent ID.
$parent = $term_id;
}
}
}
return $brands;
}