Website Building » WooCommerce » How Do I Get Product Image From Product ID in WooCommerce?

How Do I Get Product Image From Product ID in WooCommerce?

Last updated on October 1, 2022 @ 5:09 pm

If you’re running a WooCommerce store, there may come a time when you need to programmatically get the product image from a product ID. Maybe you’re creating a custom WooCommerce plugin, or perhaps you’re just writing some code to automate a task.

Whatever the reason, it’s actually quite easy to get the product image URL from a product ID in WooCommerce. All you need to do is use the WordPress wp_get_attachment_url() function.

The wp_get_attachment_url() function accepts an attachment ID as its only parameter. So all you need to do is pass in the product ID, and you’ll be able to get the URL of the product image. For example:

PRO TIP: If you are using WooCommerce to sell products on your WordPress site, you may find yourself needing to get the product image from the product ID. While this can be done with a few lines of code, it is important to be aware that doing so can have some unintended consequences.

First, if you are using any caching plugins or services, they may cache the product image based on the product ID and not the actual product image URL. This can lead to images not being updated when they should be, or even worse, displaying the wrong image entirely.

Secondly, if you are using any sort of auto-generated thumbnails or image sizes (such as WooCommerce’s built-in image sizes), these may also be based on the product ID and not the actual image URL. This means that your images may not be correctly resized and could lead to broken images on your site.

Lastly, if you change the product ID of a product (perhaps because you’ve changed the SKU), all of your product images will likely be broken as well, since they will now be pointing to a non-existent product ID.

As such, it is generally advisable to avoid getting the product image from the product ID and instead get it from the

$product_id = 123;
$product_image_url = wp_get_attachment_url( $product_id );
echo $product_image_url; // prints http://example.com/wp-content/uploads/2015/10/product-image.jpg

As you can see, this is a very simple way to get the product image URL from a product ID in WooCommerce. Of course, there are other ways to achieve this same result, but using the wp_get_attachment_url() function is by far the simplest way.

Conclusion: In order to get the product image URL from a product ID in WooCommerce, all you need to do is use the WordPress wp_get_attachment_url() function.

Morgan Bash

Morgan Bash

Technology enthusiast and Co-Founder of Women Coders SF.