Need an expert advice here. I am writing the code that updates upsell products given the criteria. For some unexplained reason, running this code deletes all variations from the product I am updating and it doe snot make sense. Here is code (i simplified it a bit for clarity)
// args contains selection criteria
$q = new WP_Query($args);
$prods = array();
if ($q->have_posts()){
while ($q->have_posts()){
$q->the_post();
$p = new WC_Product(get_the_ID());
array_push($prods, $p);
}
}
// $prods contains products I am working with
foreach ($prods as $p)
{
$upsell_ids = array();
$p->set_upsell_ids($upsell_ids);
$p->save();
}
Running this code immediately deletes all variations, but I am not even touching those. Any idea what is going on?
OK, I figured what i did wrong:
``` $p = new WC_Product(get_the_ID());```
This creates a SIMPLE product. If my original product is a variable, it effectively gets converted to a simple product. Variable products are of class WC_Product_Variable.
I found two ways to solve this problem. One is to use global $product created by the_post():
```
while ($q->have_posts()){
$q->the_post();
global $product;
array_push($prods, $product);
}```
Second way (and I prefer this one) is to let Woo to figure out correct class by using wc_get_product()
```
while ($q->have_posts()){
$q->the_post();
$p = wc_get_product(get_the_ID());
array_push($prods, $p);
}```