For various reasons, I can’t use WordPress’ built-in Thumbnail functionality.
What I want to do instead is to use the first image in the post as the thumbnail.
Here’s what I found in the codex: Show the first image associated with the post.
However, the problem with that is that if the post has multiple images, but the first image in the post is not actually the one that was uploaded first, you’ll end up getting the second image instead of the first one.
So, I decided to use something similar to this approach, which uses a regex to parse the_content
to find the first post.
This works out fine, but I end up with the image size that was used in the post, and I only want the Thumbnail size.
So, here’s the question: If I have a link to an image, is there any way I can get a different size?
Seems what I need is to somehow get the attachment ID, so that I can get the image size with this:
wp_get_attachment_link( $id, 'thumbnail' );
The problem is, how do I get an ID if all I have is the URL?
I decided to use this, which is based on @AndresYanez’s answer:
This is much more succinct (since it doesn’t jump through the hoops of first removing the extension and then adding it back in), and is a little more accurate (since the
.
is escaped and the query is case sensitive).Credits to pathorsley: http://www.pathorsley.com/code/get-the-wordpress-post-attachment-id-from-an-image-src/
The Codex is a valid source
Sometimes The Codex isn’t that wrong…
Show attachments for the current post
This is a slightly modified example from the Codex.
Be smart – use the system behind the system
The changes to the Codex example are easy: The
numberposts
are set to 1, theorderby
value is theID
and it’s sortingASC
to get the post with the lowest ID first.So here’s why this is smart: IDs are given one after each other, so the first uploaded post will have the lowest ID.
In the example above, you can simply exchange the last function with
wp_get_attachment_link()
and save it in some var, that you can reuse later.