How to hide out of stock products from the homepage in WooCommerce?

I am using WooCommerce for my store. I have a lot of products that are out of stock. All of the products shown on the homepage do not look good. I know I can go to

WooCommerce Settings → Products → Inventory

and hide out-of-stock products but this settings hide the products from everywhere. I don’t want to hide them completely. I want to hide out-of-stock products only from the homepage but keep them visible on other pages like product categories and search results. How can I do this?

To hide out-of-stock products only from the homepage in WooCommerce, you can add a small piece of code to your theme’s functions.php file. Here is cod you need to add:

add_filter('woocommerce_product_query_meta_query', function ( $meta_query ){
    if ( is_front_page() | is_home() ) {
        $meta_query[] = array(
            'key'           => '_stock_status',
            'value'         => 'instock',
            'compare'       => '='
    return $meta_query;
}, 20);