How to sort WooCommerce products page by latest in-stock items first?

There are several options.

  1. If you want to show out of stock but in latest positions you can combine your code snippet with lastest inventary order. You dont need code for this, in customizer theme usually you can change this option:

enter image description here

  1. If you want to hide out of stock and show in stock by latest. Then deleted your snippet, use same option that 1 and add this option too:

Woocommerce -> Products -> Inventary -> Hide out of stock products.

It is the best option for most stores, because it hides the products from the listings, but does not hide product page, and this does not affect seo or require additional work.

there’s also additional config to hide in serach results like explain here

Many things that a few years ago had to be done with code, Woocommrece brings that option added.

Or You can use this free plugin:
WooCommerce Sort By Stock

Regards