9

Howdy! I am looking for a way to list all of the image files in a posts' media library.

What I mean by this is if a file has been uploaded while creating or editing a post, is the file associated with the post in some way, and can I create a list from this data.

I think that the next_image_link() / previous_image_link(); template tag is as close as I have found.

I think that this should be close:

$query = 'SELECT * FROM `wp_posts` 
WHERE `post_parent` = \''.$_GET['post_id'].'\' 
AND  `post_mime_type` = \'image/jpeg\' 
ORDER BY `menu_order` ASC';

thanks.

superUntitled
  • 22,351
  • 30
  • 83
  • 110
  • 4
    **DON'T EVER DO THIS** - you are setting yourself up to have your database and/or application compromized via [SQL injections](https://en.wikipedia.org/wiki/SQL_injection). Any time you build a database query string directly from data you get from the client, *you are doing it wrong*. Always use [parameterized queries](http://stackoverflow.com/a/60496/41688). – BryanH Jul 10 '12 at 19:26

2 Answers2

12

In wordpress terminology, every image you uploaded to particular post is called attachment. To list all attachment, you can use get_children() function:

$images =& get_children( 'post_type=attachment&post_mime_type=image&post_parent=10' );

$counter=0;
foreach( (array) $images as $attachment_id => $attachment )
{
   $counter++;
   echo "<a href='".wp_get_attachment_link( $attachment_id ) . "'>image $counter</a><br />";
}

The algorithm is something like that.

ariefbayu
  • 21,849
  • 12
  • 71
  • 92
0

If you are looking for a plugin to manage image gallery, you can use attachments plugin,

http://wordpress.org/plugins/attachments/

It keeps the gallery separate and does not put the image gallery shortcodes in post content, thus providing you with full hold over image display in your post/page/custom post. You can also change the order of your images by just drag-n-drop

here is a sample code of how to retrieve your gallery images,

<?php $attachments = new Attachments( 'attachments' ); /* pass the instance name */ ?>
<?php if( $attachments->exist() ) : ?>
  <h3>Attachments</h3>
  <p>Total Attachments: <?php echo $attachments->total(); ?></p>
  <ul>
    <?php while( $attachments->get() ) : ?>
      <li>
        ID: <?php echo $attachments->id(); ?><br />
        Type: <?php echo $attachments->type(); ?><br />
        Subtype: <?php echo $attachments->subtype(); ?><br />
        URL: <?php echo $attachments->url(); ?><br />
        Image: <?php echo $attachments->image( 'thumbnail' ); ?><br />
        Source: <?php echo $attachments->src( 'full' ); ?><br />
        Size: <?php echo $attachments->filesize(); ?><br />
        Title Field: <?php echo $attachments->field( 'title' ); ?><br />
        Caption Field: <?php echo $attachments->field( 'caption' ); ?>
      </li>
    <?php endwhile; ?>
  </ul>
<?php endif; ?> 
Nagendra Rao
  • 7,016
  • 5
  • 54
  • 92