Exclude out of stock WooCommerce products from search result

WooCommerce out of stock products can be excluded from search result by using the _stock_status meta key of products. This meta key checks if a product is in stock or not. We can modify search query using pre_get_posts action hook and load only instock products.

function careless_hide_out_of_stock_products_from_search( $query ) {
    if( is_admin() ) {
        return;
    }

    if( is_search() && $query->is_main_query() ) {
        $query->set( 'meta_key', '_stock_status' );
        $query->set( 'meta_value', 'instock' );
    }

}
add_action( 'pre_get_posts', 'careless_hide_out_of_stock_products_from_search' );

Code goes in the functions.php file of your active theme.

If you want to show a nice sold out badge for out of stock products in archive pages, check this article.