I have a custom cron job that automatically updates a pre-order product to 'out of stock' when it reaches a predefined date.
Is there a way I can also add a product tag to the product as part of this cron job?
Here's the code I have for the stock status update:
// Custom Cron hooked Function called by wp_schedule_event
add_action( 'jape_pre_order_stock_update', 'update_pre_order_stock_status' );
function update_pre_order_stock_status(){
// Get all related product IDs to update via a WP_Query
$products_ids = get_posts( [
'post_type' => 'product',
'post_status' => 'publish',
'numberposts' => 100, // <= the number of products to process (-1 is all)
'fields' => 'ids',
'tax_query' => array( array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array(
'comic-book-pre-orders',
'dc-comics-pre-orders',
'image-comics-pre-orders',
'manga-pre-orders',
'marvel-comics-pre-orders',
'other-publisher-pre-orders',
),
) ),
'meta_query' => array(
'relation' => 'AND',
array(
'key' => '_stock_status',
'value' => 'instock',
'compare' => '=',
),
array(
'key' => 'woo_expiry_date',
'value' => date_i18n('Y-m-d'),
'compare' => '<=',
'type' => 'DATE',
),
array(
'key' => 'woo_expiry_action',
'value' => 'out',
'compare' => '=',
),
),
] );
foreach( $products_ids as $product_id ) {
$product = wc_get_product($product_id);
$shipping_class_id = 1002;
$product->set_stock_quantity(0); // Set stock quantity
$product->set_stock_status('outofstock'); // Set stock status
$product->set_shipping_class_id( $shipping_class_id ); // Set the shipping class ID
$product->save(); // Save updated product data
}
rocket_clean_post( $product );
}
I have this code for adding a tag when a product is sold out, but can't work out how to apply it to pre-orders in the cron job above:
// Add Out Of Stock tag to products when they sell out
function action_woocommerce_no_stock( $wc_get_product ) {
// Get current tag id(s)
$current_tag_ids = $wc_get_product->get_tag_ids();
// Product set tag id(s), multiple IDs can be added, separated by a comma
$new_tag_ids = array( '4074' );
$wc_get_product->set_tag_ids( array_unique( array_merge( $current_tag_ids, $new_tag_ids ), SORT_REGULAR ) );
// Save
$wc_get_product->save();
}
add_action( 'woocommerce_no_stock', 'action_woocommerce_no_stock', 10, 1 );
Any suggestions would be very much appreciated!
Assuming that "4074" is the desired product tag term ID, simply use inside your products foreach loop, just before the save()
method:
$product->set_tag_ids( array_unique( array_merge( $product->get_tag_ids(), [4074]) ) );
It should work.