1

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

4
  • 1
    wc_create_attribute() saves the attribute information to the database in a custom table. WooCommerce reads this table registers taxonomies for the saved attributes on the init hook at priority 5. To do what you want you need to create the attribute before init at priority 5, and then assign to to the product after init at priority 5. Sep 27, 2018 at 10:31
  • Thanks for the answer. This makes sense. Do you have any idea & example how to achieve this?
    – Benmay
    Sep 27, 2018 at 10:53
  • I don't really know what you're doing exactly. What's the context of this code? Sep 27, 2018 at 10:54
  • It's a functions which executes to create attributes/terms on a custom theme import because these are not imported on the demo import.
    – Benmay
    Sep 27, 2018 at 11:12

2 Answers 2

0

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);
0
wc_create_attribute( array(
    'name' => 'color',
    'type' => 'select'
) );

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

wp_insert_term( 'Rood', 'pa_color' );
1
  • 1
    Please edit your answer, and add an explanation: why could that solve the problem?
    – fuxia
    Nov 13, 2020 at 18:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.