How to Add a Custom Image to All WooCommerce Product Galleries

If you’ve ever needed to add a custom image to every product gallery in your WooCommerce store, you’re in the right place! Whether it’s a promotional banner, a watermark, or a universal product badge, this tutorial will show you how to achieve this programmatically with a simple PHP snippet.

The Problem

Your client wants a specific image (e.g., a “Best Seller” badge or a promotional icon) to appear in the gallery of every product on their WooCommerce store. Manually adding this image to hundreds or thousands of products would be time-consuming and impractical.

The Solution

By using a custom PHP function, you can automatically add the desired image to all product galleries in just a few steps. Here’s the code that does the magic:

How It Works

1.  Fetch All Products: The get_posts() function retrieves all WooCommerce products.
2. Define the New Image: Replace 1234 with the attachment ID of the image you want to add.
3. Update Product Galleries: The code loops through each product, checks if the image is already in the gallery, and adds it if it’s not.
4. Save Changes: The update_post_meta() function saves the updated gallery to each product.

Steps to Implement

1. Add the code to your theme’s functions.php file or a custom plugin.
2. Replace 1234 with the actual attachment ID of your custom image.
3. Save the file and refresh your website.

Why This Works

WooCommerce stores product gallery images as a comma-separated list of attachment IDs in the _product_image_gallery meta field. By programmatically updating this field, we can ensure the custom image is added to every product gallery without manual effort.

Bonus Tip

If you want to remove the image later, you can modify the code to exclude the image ID or create a separate function to reverse the process.

Conclusion

This simple yet powerful solution saves time and ensures consistency across your WooCommerce store. Whether you’re adding a promotional badge, a watermark, or any other custom image, this method makes it easy to scale across all products.

If you found this helpful, feel free to share it with others or leave a comment below. Happy coding!