Home Forums Front-end Issues Loop through fields from custom post type but limit output


Loop through fields from custom post type but limit output

  • On a project I want to display the latest gallery images from a custom post type (news) on a single page called Gallery. Each news article can have any amount of images within the field from 0 to infinite.

    Ordinarily I’d just loop through X number of posts and display a set number of images (or all) from each, but I need to be able to limit the number of images shown on this page to 12, so it effectively shows the latest 12 images from the news articles in the system. The problem with limiting the number of posts to loop or by limiting the number of images from each post is that if an article has no images then the displayed number of images will not be correct, so is there a way to loop through all images from all posts but then limit the number of actual images on the page?

    I know there is no date stamp associated with images uploaded but as long as it loops through the posts from most recent then we should be fine. I know how to loop through all posts and order by most recent, it’s just the limiting the total number of images displayed on the page to 12 I’m not sure about.

    Any help guys?

  • Loop over the posts. Instead of showing the images inside the loop collect the image information in an array. When you have 12 images collected in the array break out of the posts loop. Create a second loop to loop over the images and display.

    Or simply keep a running count of the images that have been shown with a counter and break out of the loop when the counter hits 12.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.