Where to add my code to auto attach images to existing products

Most likely, all you need to do is add this to your theme’s functions.php file.

However, you should also be aware that if you didn’t create this theme and you update it, these modifications will be overridden. You can apply them again, but a better method for this (as I’ve explained a bit more in this answer) is to create a child theme.

Alternatively, if this is the only modification you are wanting to make, it might actually be easier to turn the code into a basic plugin. Add it into a blank file, call it whatever-you-like.php and put it directly into the wp-content/plugins/ folder. At the top of the file, after the opening <?php tag, add this code:

/* Plugin Name: Match Images to Pre-existing Products */

Then, on your plugin page, you’ll see this plugin come up – and you can activate and de-activate it at will.

The bonus of this second method is you can do this for other modifications you make as well, and then easily activate/deactivate them independently when you require them.