Wordpress services, tutorials and news

How to display an image in WordPress if you know the image attachment id

Do you need to display an image inside a post using code, but it’s not the featured post image? It can be done if you know the image attachment ID.

Each time you upload an image in the WordPress media gallery, WordPress actually creates a new post in the wp_posts table. It has an ID like a normal post, but if the post_type field has the value “attachment”. If you know the ID of this post, then we can display the image using code, anywhere in a post of page, even if the image is not the featured image.

Let’s say we have some code where we find out the ID of the image, and we define a variable $profilepicture that has the ID value. We then can use wp_get_attachment_image to display the actual image like so:

echo wp_get_attachment_image( $profilepicture, 'medium', "", array( "class" => "alignright size-medium" ) );

The values from above are: the post id, size (in this case we use the standard medium size),whether the image should be treated as an icon (which defaults to false so I’ve put “”) and attributes for the image markup – I only used the class array.

This will output the following HTML code, for example:

<img loading=”lazy” class=”aligncenter size-full wp-image-734 lazy loaded” src=”https://www.wp-starter.com/wp-content/uploads/wordpress-datepicker.png” data-src=”https://www.wp-starter.com/wp-content/uploads/wordpress-datepicker.png” alt=”” data-srcset=”https://www.wp-starter.com/wp-content/uploads/wordpress-datepicker.png 1063w, https://www.wp-starter.com/wp-content/uploads/wordpress-datepicker-300×142.png 300w, https://www.wp-starter.com/wp-content/uploads/wordpress-datepicker-1024×486.png 1024w, https://www.wp-starter.com/wp-content/uploads/wordpress-datepicker-768×364.png 768w” data-sizes=”(max-width: 1063px) 100vw, 1063px” sizes=”(max-width: 1063px) 100vw, 1063px” srcset=”https://www.wp-starter.com/wp-content/uploads/wordpress-datepicker.png 1063w, https://www.wp-starter.com/wp-content/uploads/wordpress-datepicker-300×142.png 300w, https://www.wp-starter.com/wp-content/uploads/wordpress-datepicker-1024×486.png 1024w, https://www.wp-starter.com/wp-content/uploads/wordpress-datepicker-768×364.png 768w” data-was-processed=”true” width=”1063″ height=”504″>

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: