I'm passing an array of product IDs (as integers) into the below function, which also accepts the current category ID. This gets ran on the product category edit screen in the WordPress/WooCommerce admin and is basically just a quick way to assign multiple products to the current category. The idea is that any of these products that are not currently in this category, get assigned to the category.
This is working to a point. When I var dump the product objects it is showing the newly added category and the category is ticked in the product edit screen. However, when viewing the category on the frontend, the products are not showing up. Then, going into the site admin, editing the product (with no changes) and updating it then has it show in the category on the frontend. So it seems that the product needs to be saved before it will show up but that shouldn't be the case, and still doesn't work when programatically saving the product in the below function.
I added an if
statement to also add the children to the category just to rule that out but that doesn't help.
Can somebody please give me a sanity check on this?
function spc_assign_new_products($term_id, $product_ids)
{
$new_products = wc_get_products([
'limit' => -1,
'include' => $product_ids,
'status' => 'publish',
'tax_query' => [
[
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => [$term_id],
'operator' => 'NOT IN',
'include_children' => false,
]
],
]);
foreach ($new_products as $product) {
wp_set_object_terms($product->get_id(), (int) $term_id, 'product_cat', true);
if ($children = $product->get_children()) {
foreach ($children as $child_id) {
wp_set_object_terms($child_id, (int) $term_id, 'product_cat', true);
}
}
}
}
Var dumping product objects before and after hitting update in the admin doesn't show any differences other than modified timestamps so I'm at a loss. I've also ruled out caching, having it totally disabled on the local dev site.