Not sure that you are using the correct hook…
When a product is back in stock, WooCommerce remove outofstock term (term id) for "product_visibility" taxonomy from post term relationship and also set post meta data value to "instock" for _stock_status
meta key.
To remove post term relationship you certainly use wp_remove_object_terms()
function.
So you need to make some changes in your 2nd function to make variable products in stock when any of its variations is in stock (untested):
add_action( 'woocommerce_after_shop_loop_item', 'show_hide_variable_product_based_on_stock', 9 );
function show_hide_variable_product_based_on_stock() {
global $product;
$product_id = $product->get_id();
$is_prod_in_stock = is_wc_variable_product_in_stock( $product->get_id() );
$current_status = get_post_meta( $product_id, '_stock_status', true );
$status_to_set = '';
if ( $product->is_type('variable') ) {
$status_to_set = '';
if ( ! $is_prod_in_stock && $current_status === 'instock' ) {
$status_to_set = 'outofstock';
} elseif ( $is_prod_in_stock && $current_status === 'outofstock' ) {
$status_to_set = 'instock';
} else {
$status_to_set = '';
}
if ( ! empty($status_to_set) ) {
// Updating the product status (meta data)
update_post_meta( $product_id, '_stock_status', $status_to_set );
// Add or Remove "outofstock" post term relationship for "product_visibility" taxonomy
if( $status_to_set === 'outofstock' ) {
wp_set_post_terms( $product_id, 'outofstock', 'product_visibility', true ); // Add
} else {
wp_remove_object_terms( $product_id, 'outofstock', 'product_visibility' ); // Remove
}
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…