You can hide out-of-stock products from catalog and search pages. The simplest way is through WooCommerce settings: WooCommerce > Settings > Products > Inventory > “Hide out of stock items from the catalog”. If you prefer a code-based approach, add to your functions.php. For more on managing stock in WooCommerce.
add_action( 'pre_get_posts', function( $query ) {
if ( ! is_admin() && $query->is_main_query() && ( is_shop() || is_product_category() || is_product_tag() ) ) {
$query->set( 'meta_query', array(
array(
'key' => '_stock_status',
'value' => 'instock',
'compare' => '=',
),
) );
}
} );