Those of you who use Toolset may have been stuck wanting to show an alternative image size from an Image field value. Only the full size image URL is presented as the meta value and while WordPress has A LOT of handy functions within its core, this is something it lacks.

Of course you could get round this by storing the media ID in the field, but out of the box Toolset doesnt. When I started using Toolset i was stuck with this problem for a while and then I found this snippet by Pippins over at https://pippinsplugins.com/retrieve-attachment-id-from-image-url/. While many WordPress DEVs scream cheat for using mySQL queries, it seems this is the only way to do it.

This code sample adds a little extra to Pippins initial snippet, rather than just recalling the ID this will return the URL of the desired size.

All the credit for this one is with Pippins!

Code Example

Its a pretty simple little snippet with 2 steps.
  • Searches the database for any entries matching the URL supplied
  • Returns attachment ID
  • Returns the URL for the image in the desired format ($format)
You can create new image sizes using add_img_size. Remember alternative images sizes are generated for already uploaded images using add_img_size (so make sure you set your images before you begin adding content)

Post comment