WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I need to retrieve the URLs for the images inside a gallery, what's the appropriate SQL query for this, based on the post ID?

I currently have something like the following which I found on via google, but I don't know how to access the global WP variable from outside Wordpress - what do I need to do?

function getGallery($id)
 global $wpdb;

 //SQL query to retrieve all attachment of mime type image/jpeg from the given post
 $querystr = "
     SELECT ID, post_name, guid, meta_value
     FROM $wpdb->posts wposts
     INNER JOIN $wpdb->postmeta meta ON meta.post_id = wposts.ID AND meta.meta_key = '_wp_attachment_metadata'
     WHERE wposts.post_type = 'attachment'
     AND wposts.post_parent = '".$id."'
     AND wposts.post_mime_type = 'image/jpeg' 

 //get result set from the query
 $pictures = $wpdb->get_results($querystr, ARRAY_A);

 //return resultset
 return $pictures;
share|improve this question
I also found this wpengineer.com/1038/embed-wordpress-functions-outside-wordpress on how to use the function outside of Wordpress! – Zolomon Oct 24 '10 at 15:40
up vote 2 down vote accepted

I believe the function is wp_get_attachment_url(). There also is one for thumbnails. See wp-includes/media.php.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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