First things first: This is my first question posted on stackoverflow. Put another way, this is the first problem I could not solve by myself with your help (huge thanks to all of you, you make the world go round!).
My question is related to an answer given by @LoictheAztec to another question (I originally planned to post my question in the comments of that post but being the lurker that I am/was, I lack the reputation to do so): https://stackoverflow.com/a/47766413/13263330
I have created a variable product and would like to add new attribute values to this product programmatically.
I copied and slightly modified the code from the link above but when I tried to execute it, I received the following errors:
Notice: wc_get_product was called incorrectly. wc_get_product should not be called before the woocommerce_init, woocommerce_after_register_taxonomy and woocommerce_after_register_post_type actions have finished. Backtrace: require_once('wp-load.php'), require_once('wp-config.php'), require_once('wp-settings.php'), do_action('plugins_loaded'), WP_Hook->do_action, WP_Hook->apply_filters, execute_active_snippets, execute_snippet, eval, create_product_variation, wc_get_product, wc_doing_it_wrong
Fatal error: Uncaught Error: Call to a member function get_name() on boolean
The problem mainly seems to be about the following line of code in the link posted above:
'post_title' => $product->get_name()
Just as a reminder and for convenience reasons, the product variable is defined as follows:
$product = wc_get_product($product_id)
The attribute values are correctly added to the variable product, so the code does what I expected and intended it to do but the site still crashes.
As far as I understand the situation, problems (and their causes) occuring could be related to:
- The modifications I made in the code (already checked with default code and example given by @LoictheAztec within his post, same problem)
- As always, compatibility issues with plugins and/or theme (already checked, deactivated all other plugins and changed to default theme; also tried code with fresh WP installation)
- According to an answer given to someone having a similar problem (https://github.com/woocommerce/woocommerce/issues/23160), the issue can also be caused by the $product variable not being correctly "associated with a valid product" (not sure about this one but I think the "parent" variable product already created is fine) or "the product no longer existing" (can definitely rule this one out).
Any help whatsoever is highly appreciated.