Hide Shipping methods when Shipping classes (exist) / (do not exist) in cart.
The below code snippet can be used to hide shipping methods based on whether shipping classes are present in cart or not.
Add the following code to your functions.php or anywhere relevant.
If you are looking for a plugin to do this job, visit ELEX Hide Shipping Methods Plugin. Using this plugin, You can easily hide shipping methods based on various conditions.
You can do that pretty easily. Just go to Products –> Shipping Classes and you will find the corresponding Shipping ID for a shipping class as shown in the two screenshots below :
A small window called developers tools will open at the bottom of the page. You can find the service code from here.