Tutorial: How to get image path on a post in WordPress efficiently

This is something that WordPress currently doesn't support yet. You will face the problem of retrieving image on a particular post on the loop while you are working on WordPress theme or plugin. WordPress doesn't provides you with a method that you can use to retrieve the images on the post and you would have to search all over the internet to find someone sharing their secret with you. Thus, rather than using a complex or methods built by others, i personally have a much simple and efficient way of doing this.

The Problem

I wanted to retrieve all images on a particular post under a category and make it into a gallery. However, WordPress doesn't provides such method. Furthermore, the methods provide by others seems to complex this particular function. I want a simple and efficient way of doing this. Not a redundant one.

7 thoughts on “Tutorial: How to get image path on a post in WordPress efficiently

  1. Is it more performant than using a function ?
    I actually use one wich find me the first image of a post.
    I guess I can use regular exprssion to accomplish this, but before trying learning it, I would know if it's worth the pain 🙂 !

  2. it is definitely better using a regular expression. Imagine having 20 line of code in a function compare to 1-4 lines in regular expression. Furthermore, searching usually uses regular expression to further enhance the performance. No loop is the best.

  3. Thanks for answer 🙂 !
    I read a bit about regex, I try to understand. It's a big challenge for non-coder. How would you display only the first image ?
    I made some tutorials, but can't figure out how to say "only the first chain you find, please" !
    I now understand why regex are so rare in WP functions...

  4. hahaha..ya regex is quite challenging but practice make perfect. The easily way without writing a new code is to add in a break; in the loop after it has done with the first image 🙂

Comments are closed.