The right way to get and display all images from wordpress media library, display all images attached to posts in wordpress without plugin and easily, display all images in any place, and make shortcode to display all images in your post.

How To Display All Images From WordPress Library

Using get_posts() function and wp_get_attachment_image() function and wp_get_attachment_url() function, we will get and display all images from wordpress media library without plugin, and we will make shortcode.

Display All Images

Copy function code and paste it in your functions.php file, function code:

function WPTime_get_all_images(){
    $args = array(
        'post_type' => 'attachment',
        'numberposts' => -1, // if -1 will be display all images (unlimited), you can change it to for example 50, will be display recent 50 images only.
        'post_status' => null,
        'post_parent' => null,
        'post_mime_type' => array('image/png', 'image/x-png', 'image/jpeg', 'image/jpg') // you can add to array 'image/gif' to display gif images, or 'video/mp4' or any mime type.
    );

    $images = get_posts($args);
    $size = 'full'; // you can change size to 'large' or 'medium' or 'thumbnail'

    foreach($images as $image){
        $url = wp_get_attachment_url($image->ID); // get image url, you can remove it if you want.
        echo '<p><a href="'.$url.'">'.wp_get_attachment_image($image->ID, $size).'</a></p>';
        /*
            you can use:
            echo '<div class="my-wrap"><img class="my-custom-class" src="'.wp_get_attachment_url($image->ID).'"></div>';
        */
    }

    wp_reset_postdata();
}

Please note: if ‘numberposts’ => -1 will be display all images, if you change it to for example “20” will be display recent 20 images, you can remove ‘<p><a href=”‘.$url.'”></a></p>’ or change wrap if you want, you can change size to ‘large’ or ‘medium’ or ‘thumbnail’.

Usage

You can display all images in any place, just paste this line:

<?php WPTime_get_all_images(); ?>

And you can make shortcode and use it to display all images in your posts:

function get_all_images_shortcode(){
    ob_start();
    WPTime_get_all_images();
    return ob_get_clean();
}
add_shortcode('all_images', 'get_all_images_shortcode');

Now use this shortcode [all_images] in your post or page.