Sam
Sam

Reputation: 356

HTML Error Using wp_get_attachment_image

This code :

$src = wp_get_attachment_image( get_the_ID(), 'medium' );
$url = wp_get_attachment_image_url( get_the_ID(), 'full' );

printf( '<p><a href="%s"><img src="%s"></a></p>', $url, $src ); 

Produces this :

enter image description here

Which is this HTML

<a href="http://www.dev.dev/wp-content/uploads/2017/12/p.png"><img src="<img width=" 300"="" class="attachment-medium size-medium" alt="" srcset="http://www.dev.dev/wp-content/uploads/2017/12/p-300x169.png 300w, http://www.dev.dev/wp-content/uploads/2017/12/p-768x432.png 768w, http://www.dev.dev/wp-content/uploads/2017/12/p-1024x576.png 1024w" sizes="(max-width: 300px) 100vw, 300px" height="169">"&gt;</a>

Why is this?

I cannot see any problem with this code :

printf( '<p><a href="%s"><img src="%s"></a></p>', $url, $src );

Upvotes: 1

Views: 330

Answers (2)

Sam
Sam

Reputation: 356

This is what i changed it to. Thanks for the point in the right direction B.Desai

 printf( '<p><a href="%s">%s</a></p>', $url, $src );

wp_get_attachment_image returns (string) HTML img element or empty string on failure.

Upvotes: 0

B. Desai
B. Desai

Reputation: 16446

wp_get_attachment_image return full image tag. So You don't need to add <img src tag. Change your code

printf( '<p><a href="%s"><img src="%s"></a></p>', $url, $src ); 

to

printf( '<p><a href="%s">"%s"</a></p>', $url, $src ); 

Upvotes: 3

Related Questions