1

I am trying to make things work like where any post attachment image will generate embed code automatically.

Example: If I upload and add two images 1. 250x150 2. 600 x 160 and insert into post. Now that image information I want to auto put into embed code like below.

<div>
<a href="link url" title="title text" target="_blank"><img src="$image_url" width="$image_width" height="$image_height" alt="$image_name" /></a>
</div>

where $variable is the data of the attached image/s.

So above code our team member can use the embed code to display image.

1
  • You'll need to write a plugin. Is that something you're looking to do? May 10, 2012 at 18:12

1 Answer 1

3

WordPress has a predefined function, wp_get_attachment_image_src that returns the following information as an array:

[0] => url
[1] => width
[2] => height

But, the function requires that you know the attachment's ID, not the post's ID. In order to get that, you'll need to use get_post_thumbnail_id.

Here's the two functions together in action:

$image_id = get_post_thumbnail_id($post->ID);
$image = wp_get_attachment_image_src($image_id);

After that, you can easily do what you're talking about in your question.

<img src="$image[0]" width="$image[1]" height="$image[2]" />

If you want more information about the wp_get_attachment_image_src, you can read more about it here: http://codex.wordpress.org/Function_Reference/wp_get_attachment_image_src.

6
  • Cool this is working completely fine but only one issue. I want to get size from post attachments it could be one or more and not from the thumbnail. Can you please help to do that. Also how to get image alt="" dynamically same like height width and src May 11, 2012 at 6:06
  • Its done I used $attachments = get_posts($args); to get all attachments and used foreach and it works great. Thanks a lot. May 11, 2012 at 8:02
  • I'm really happy that I could set you on the right path.
    – Alex Lane
    May 11, 2012 at 13:36
  • Quickly related question. Now I want to get size of the attached image/s I mean in kb/mb. I want to display image kb on post. How can I get that? May 18, 2012 at 5:42
  • 1
    There's a PHP function called filesize() than can return the size of a file in bytes, but it looks like you have to supply a PATH and not a URL. I'll keep looking into it, but this seems a little trickier. You might want to open another question.
    – Alex Lane
    May 18, 2012 at 12:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.