I have created 3 tags 1.
I would like these tags to be auto-assigned based on availability.
If I am able to get this working, I'll be using the woocommerce_admin_process_product_object
, woocommerce_product_quick_edit_save
, woocommerce_product_set_stock
, woocommerce_variation_set_stock
to capture the possible scenarios for stock status changes.
Below is what I have tried but it gives me a fatal error. If I do not use the if condition, then the tags get assigned but it does not meet my objective. Any advice?
add_action( 'woocommerce_admin_process_product_object', 'mycode_woocommerce_backorder_tag', 10, 2 );
function mycode_woocommerce_backorder_tag ($wc_get_product, $product) {
if ($product->managing_stock() && $product->is_on_backorder(1)) {
$wc_get_product->set_tag_ids(array(111));
$wc_get_product->save();
//wp_set_object_terms ($post_id, 'onbackorder', 'product_tag');
}
}
woocommerce_admin_process_product_object
hook has only 1 argument, which is $product
$product->save();
is also not necessary, because this happens automatically
Copied from admin/meta-boxes/class-wc-meta-box-product-data.php
/**
* Set props before save.
*
* @since 3.0.0
*/
do_action( 'woocommerce_admin_process_product_object', $product );
$product->save();
So to answer your question, you get:
// When product is saved in WooCommerce backend
function action_woocommerce_admin_process_product_object( $product ) {
// managing_stock() - returns whether or not the product is stock managed.
// on_backorder() – check if a product is on backorder.
if ( $product->managing_stock() && $product->is_on_backorder(1) ) {
// Product set tag ids
$product->set_tag_ids( array( 111 ) );
}
}
add_action( 'woocommerce_admin_process_product_object', 'action_woocommerce_admin_process_product_object', 10, 1 );