Error while creating woocommerce product category

Viewed 164

Running wordpress locally and try to create category for woocommerce product

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

Error is this

object(WP_Error)#629 (3) { ["errors"]=> array(1) { ["invalid_taxonomy"]=> array(1) { [0]=> string(17) "Invalid taxonomy." } } ["error_data"]=> array(0) { } ["additional_data":protected]=> array(0) { } }

1 Answers

It depends on when you try to input the term as the WooCommerce taxonomy product_cat is not there at different stages of the WP initialization process.

Example at WordPress init hook:

add_action('init', function() {
  var_dump(taxonomy_exists( 'product_cat' ));
});
bool(false)

whereas running the same for example in the woocommerce_before_main_content hook of WooCommerce:

bool(true)

The earliest point in time when your statement will work is with the action/hook called woocommerce_after_register_taxonomy (see WooCommerce GitHub Repository) because all core WooCommerce taxonomies are created by then.

At which point in time are you trying to add the term to the taxonomy?

Related