I need to set product’s attributes via PHP code.
According to other threads on StackOverflow, there’s the method wp_set_object_terms. Unfortunately it is not working as it is supposed to do in my case:
For example, there is an attribute named “Hersteller”, slug “hersteller”.
And there is a product, ID 593, with no “hersteller” attribute set.
I tried the following code to fill the attribute:
wp_set_object_terms(593, 'Alpina', 'pa_hersteller' , false);
When I’m attempting to display the attribute on the product page, there is no output, so it seems that the wp_set_object_terms process hasn’t been successful.
Following code produces an empty output:
$product->get_attribute('hersteller');
Furthermore, the attribute “hersteller” isn’t even listed in the attribute list in the admin backend menue.
To debug the problem I’ve also tried the following code:
$attributes = get_post_meta( 593, '_product_attributes' );
print_r($attributes);
resulting in the following output:
Array ( [0] => Array ( [pa_marken] => Array ( [name] => pa_marken [value] => [position] => 0 [is_visible] => 1 [is_variation] => 0 [is_taxonomy] => 1 ) [pa_kategorien] => Array ( [name] => pa_kategorien [value] => [position] => 1 [is_visible] => 1 [is_variation] => 0 [is_taxonomy] => 1 ) [pa_referenznummer] => Array ( [name] => pa_referenznummer [value] => [position] => 2 [is_visible] => 1 [is_variation] => 0 [is_taxonomy] => 1 ) [pa_herstellergarantie] => Array ( [name] => pa_herstellergarantie [value] => [position] => 3 [is_visible] => 1 [is_variation] => 0 [is_taxonomy] => 1 ) [pa_schlagwoerter] => Array ( [name] => pa_schlagwoerter [value] => [position] => 4 [is_visible] => 1 [is_variation] => 0 [is_taxonomy] => 1 ) [pa_lieferzeit] => Array ( [name] => pa_lieferzeit [value] => [position] => 5 [is_visible] => 1 [is_variation] => 0 [is_taxonomy] => 1 ) ) )
Am I using the wp_set_object_terms method essentially wrong?
I don’t know what to do anymore now. May anyone here can help me? Thanks!
Try to set your code like this:
And try again.
According to the function in WordPress Codex
So if you change the $append to true it may be works =)
Based on the attributes output you provided, it seems that you are targeting the wrong taxonomy, I can see
pa_herstellergarantie
in the following output :Change your code to:
Also a note to say that
wp_set_object_terms
will not create the taxonomy.If the taxonomy doesn’t exist it will throw an
Invalid taxonomy
error message.If
pa_herstellergarantie
andpa_hersteller
are 2 distinct taxonomies, then ensure thatpa_hersteller
exists before usingwp_set_object_terms
To set attributes programatically you must update the post meta with the taxonomy’s data after setting the terms, like this
Hope it helps 🙂