WP_Error on attribute + term insert

I want to add a product attribute (wc_create_attribute) assigned terms (wp_insert_term) via the functions.php.

Example:

$args = array(
  'name'         = "Color",
  'slug'         = "color",
  'order_by'     = "menu_order",
  'has_archives' = "",
);
wc_create_attribute($args);

$add = wp_insert_term( "Blue", 'pa_color', array( 'slug' = "blue" ) );
print_r($add);

The wc_create_attribute() works fine, but when the wp_insert_term() runs it throws an error because of “Invalid taxonomy”. When I then reload the page, it works fine because then the taxonomy is not invalid anymore. So it seems that the wp_insert_term() are executed before the create_attribute somehow. I don’t understand why it does not work in one attempt.

Maybe you can help me

Topic woocommerce-offtopic terms Wordpress

Category Web


wc_create_attribute( array(
    'name' => 'color',
    'type' => 'select'
) );

register_taxonomy( 'pa_color', array( 'product' ), array() );

wp_insert_term( 'Rood', 'pa_color' );

Try to reregister taxonomies

$args = array(
  'name'         => "Color",
  'slug'         => "color",
  'order_by'     => "menu_order",
  'has_archives' => "",
);
wc_create_attribute($args);
WC_Post_Types::register_taxonomies();

$add = wp_insert_term( "Blue", 'pa_color', array( 'slug' => "blue" ) );
print_r($add);

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.