15

Can anyone suggest me what is the function to get all the images stored for wordpress? I just need to list all the images seen under menu Media of the wordpress admin.

Thanks in advance

2 Answers 2

36

Uploaded images are stored as posts with the type "attachment"; use get_posts() with the right parameters. In the Codex entry for get_posts(), this example:

<?php

$args = array(
    'post_type' => 'attachment',
    'numberposts' => -1,
    'post_status' => null,
    'post_parent' => null, // any parent
    ); 
$attachments = get_posts($args);
if ($attachments) {
    foreach ($attachments as $post) {
        setup_postdata($post);
        the_title();
        the_attachment_link($post->ID, false);
        the_excerpt();
    }
}

?>

...loops through all the attachments and displays them.

If you just want to get images, as TheDeadMedic commented, you can filter with 'post_mime_type' => 'image' in the arguments.

4
  • 5
    Yup, you can just use 'post_mime_type' => 'image' in your $args, and WordPress will cleverly match that against all image mime types :) Commented Jul 22, 2010 at 11:31
  • 1
    @TheDeadMedic Good to know! I've never needed to get particular types back. Commented Jul 22, 2010 at 12:05
  • Nice answer and kudos to TheDeadMedic for matching mime types! :) Commented Jul 22, 2010 at 12:17
  • 1
    null didn't work for me with the current version of WP, but 'any' did the trick.
    – Denis V
    Commented Feb 13, 2014 at 20:51
2
<ul>
            <?php if ( have_posts() ) : while ( have_posts() ) : the_post();    

                    $args = array(
                        'post_type' => 'attachment',
                        'numberposts' => -1,
                        'post_status' => null,
                        'post_parent' => $post->ID
                        );

                    $attachments = get_posts( $args );
                    if ( $attachments ) {
                        foreach ( $attachments as $attachment ) {
                            echo '<li>';
                            echo wp_get_attachment_image( $attachment->ID, 'full' );
                            echo '<p>';
                            echo apply_filters( 'the_title', $attachment->post_title );
                            echo '</p></li>';
                        }
                    }

            endwhile; endif; ?>
        </ul>
1
  • Do I need to make a new page? Commented Sep 19, 2016 at 5:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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