Is it possible to execute this php function when product is updated via Cron Job or REST_API? Cron JOB is updating _stock2 meta field, and rest_api is updating basic stock quantity of woocommerce product.
add_action('woocommerce_admin_process_product_object', 'update_product_tag_on_stock_change');
function update_product_tag_on_stock_change($product) {
// Debugging: Log message to check if the function is being called
error_log('Function update_product_tag_on_stock_change called.');
if ($product->is_type('variable')) {
$variations = $product->get_children();
$total_stock_quantity = 0;
$total_stock_quantity2 = 0;
foreach ($variations as $variation_id) {
$variation = wc_get_product($variation_id);
$total_stock_quantity += intval($variation->get_stock_quantity()) - intval($variation->get_meta('_stock2'));
$total_stock_quantity2 += intval($variation->get_meta('_stock2'));
}
// Debugging: Log total_stock_quantity and total_stock_quantity2
error_log('Total Stock Quantity: ' . $total_stock_quantity);
error_log('Total Stock Quantity2: ' . $total_stock_quantity2);
if ($total_stock_quantity2 > 0 && $total_stock_quantity < 2) {
wp_set_object_terms($product->get_id(), '3-5dni', 'product_tag', true);
// Debugging: Log message when tag is set
error_log('Tag set to 3-5dni');
} else {
wp_remove_object_terms($product->get_id(), '3-5dni', 'product_tag', true);
// Debugging: Log message when tag is removed
error_log('Tag removed from 3-5dni');
}
} else {
$stock_quantity = intval($product->get_stock_quantity()) - intval($product->get_meta('_stock2'));
$stock_quantity2 = intval($product->get_meta('_stock2'));
// Debugging: Log stock_quantity and stock_quantity2
error_log('Stock Quantity: ' . $stock_quantity);
error_log('Stock Quantity2: ' . $stock_quantity2);
if ($stock_quantity2 > 0 && $stock_quantity < 2) {
wp_set_object_terms($product->get_id(), '3-5dni', 'product_tag', true);
// Debugging: Log message when tag is set
error_log('Tag set to 3-5dni');
} else {
wp_remove_object_terms($product->get_id(), '3-5dni', 'product_tag', true);
// Debugging: Log message when tag is removed
error_log('Tag removed from 3-5dni');
}
}
}
Now this function works only if I update product manualy via admin page.
Your action specifically targets the admin processing of the object, so it won't execute unless this hook is being executed:
woocommerce_admin_process_product_objectHowever, there are specific hooks you could target in addition to the one you have above and you could have your function added to multiple hooks: