How to Get Product Image src WooCommerce

WooCommerce Get Product Image src

If you are looking for a quick and easy way you display the WooCommerce product image, you need to know how to use the WooCommerce to get product image src code I will share in this post. WooCommerce product has the main image and the gallery images.

If you want to change how they are displayed, you need to understand how to get WooCommerce product src.

WooCommerce Get Product Image src

As I have mentioned before WooCommerce is a custom post type and the main image on the single page is simply the featured image just like the featured image in another post like the ordinary WordPress post.

You can use the following code snippet to get the URL of the featured image of the current product :

if ( has_post_thumbnail( $post->ID) ) {
echo wp_get_attachment_url( get_post_thumbnail_id( $post->ID ) );
}

The first step in my code is to get the current product ID.  I have used the global post object and accessed the ID property as shown in the code below :

global $post;

echo $post->ID;

As you can see the code when added to a wp_header action hook can display the product id as shown in the image below:

woocommerce get product image src 1

 

Now you can add the full code to the header to illustrate how the URL of the product image will be displayed and the full code to the header is as follows:

 

add_action('wp_head', 'display_example_code_header_');

function display_example_code_header_(){

global $post;

if ( has_post_thumbnail( $post->ID) ) {
echo wp_get_attachment_url( get_post_thumbnail_id( $post->ID ) );
}
}

When you add this code you should see the product image src displayed on the header as shown in the image below :

woocommerce get product image src 2

Conclusion

In this post, we have looked at how to get the product image src in WooCommerce.

The take from this tutorial is the function that gets the product image and also the ID of the product or the post.

Those are the two requirements that make the magic happen. You can go ahead and use this URL to display the image or customize it to fit your design.

Similar Articles