So none of the answers here were good enough for me. Unless your email address ends in '@magento.com', you should not be using Object Manager in your code. No ifs, no buts. This is how I went about achieving this:
If you're using magento 2.4 then you have to create a plugin for
We have to set the Go to Stores > Configuration > Catalog > Inventory > Stock Options->Display Out of Stock Products. This is necessary because Magento doesn't load the is_in_stock filters when we set this option to 'NO'. So we can't put our custom ...
In your theme go to etc/view.xml add the following code , if code is already exist, kindly use "replace" instead "prepend"
<vars module="Magento_ConfigurableProduct"><var name="gallery_switch_strategy">replace</var></vars>