What is the function got get all the media files w

2020-02-02 12:54发布

问题:

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

回答1:

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.



回答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>