I want to get all images in the image gallery with pagination so that I can use infinite-scroll with it.

The infinite scroll works but it's taking the posts' number of post, not the images. That means that if I have 6 posts, and the "Blog pages show at most" is 2, the number of pages will be 3, even if I have more images to load.

I'm also using FoundationPress as a framework if that helps.

here's my code:


            $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
            $args = array(
                'posts_per_page' => 10,
                'post_type' => 'attachment',
                'paged'     => $paged

            $attachments = get_posts( $args );
            if ( $attachments ) {
                foreach ( $attachments as $attachment ) {
                    $ia = wp_get_attachment_image_src( $attachment->ID, 'full' );
                    <div class="grid__item">
                        <figure width="<?php echo $ia[1]; ?>" height="<?php echo $ia[2]; ?>">
                            <?php echo wp_get_attachment_image( $attachment->ID, 'full' ); ?>


1 Answer 1


EDIT: I didn't read your code properly, sorry!

You're using get posts which will only retrieve posts. To get all the images from the media library you'll need to use WP_query.

$query_images_args = array(
    'post_type' => 'attachment',
    'post_mime_type' =>'image',
    'post_status' => 'inherit',
    'posts_per_page' => -1,

$query_images = new WP_Query( $query_images_args );
$images = array();
foreach ( $query_images->posts as $image) {
    $images[]= wp_get_attachment_url( $image->ID );

This code will put all the URLs of images from the media library into the $images array.

ref: https://wpeden.com/tipsntuts/list-all-images-at-media-gallery-in-your-wordpress-site/

  • The page is still assuming the number of posts, not the number of attachments. Commented Oct 27, 2017 at 10:33
  • Hi - sorry I missed the get posts part of your question. Commented Oct 27, 2017 at 10:42
  • Ok, this is just another way of loading the images. It did load the images on my code too the problem is that it pagination is incorrect. I pasted your code into mine, the images worked but the pagination is still incorrect. Commented Oct 27, 2017 at 10:55
  • Actually the pagination doesn't appear anymore without the get post. So I'm not sure if I need to edit the pagination function. Commented Oct 27, 2017 at 10:59
  • Have you set up your pagination? There are some plugins you can use if you aren't comfortable making your own. Here's an example en-gb.wordpress.org/plugins/wp-paginate Commented Oct 30, 2017 at 9:16

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.