Essy Telle
Essy Telle

Reputation: 1

Is there a function in woocommerce to create programmatically a category for a product?

I would like to attach a category to a product and create that category if it does not exist. There is my code. The issue is that the wp_insert function can't read the variable i passed

$products = array(
    'id' => 1,
    'label' => 'tecno xyz',
    'price' => 1250 ,
    'category' => array(
        'id' => 1,
        'label' => 'high tech')
     );
$category = $products['category']['label'];

$testCateg = is_product_category([$term = $category]);
if (!$testCateg) {
    wp_insert_term(
      $category, // the term 
      'product_cat', // the taxonomy
      array(
        'description'=> 'New New Category description for testing purpose'
        //'slug' => 'new-category'
      )
    );
}

Upvotes: 0

Views: 1031

Answers (1)

dilico
dilico

Reputation: 754

To check if a product category exists, don't use is_product_category, as that function is used to check if a certain product category page is displayed (see WooCommerce conditional tags for a list of tags available on each page).

Product category is a custom taxonomy (product_cat) used by WooCommerce, so the existing product categories can be retrieved simply using get_terms. For example, adding a new category if it doesn't already exist can be achieved like this:

function add_product_category() {
  $new_product = array(
    'id' => 1,
    'label' => 'tecno xyz',
    'price' => 1250,
    'category' => array(
      'id' => 1,
      'label' => 'high tech',
    ),
  );
  $category = $new_product['category']['label'];
  $args = array(
    'hide_empty' => false,
  );
  $product_categories = get_terms( 'product_cat', $args );
  foreach ( $product_categories as $key => $product_category ) {
    if ( $product_category->name === $category ) {
      return;
    }
  }
  $term = wp_insert_term(
    $category,
    'product_cat',
    array(
      'description' => 'New Category description for testing purpose',
    ),
  );
  if ( is_wp_error( $term ) ) {
    // do something with error.
  }
}

Upvotes: 1

Related Questions