Categories:> WordPress

How to limit WordPress gallery thumbnails in the loop

Today I stumbled upon a problem, which I think it should be common sense to have in WordPress. I wanted to list the default WordPress image galleries from posts in the loop, but I couldn’t find any shortcode to limit the displayed number of thumbnails. After spending 2 hours on research I’ve found some solutions to this problem, but I had to dig in to the functions.php of my theme.

The solution is to modify the GALLERY shortcode with filters from your functions.php file and then define in a variable how many thumbnails you want in the loop, which will be interpreted by a function.

Here’s the function you need to create in the functions.php of your theme file:

function get_random_gallery_images(){
	global $wpdb,$post;
		$ids = "";
		$counter = 0;
		$number_of_posts = 4;
		$args = array(
		'post_type' => 'attachment',
		'numberposts' => 4,
		'post_status' => null,
		'orderby' => 'rand',
		'post_parent' => $post->ID
		);
		$attachments = get_posts($args);
		if ($attachments) {
			foreach ($attachments as $attachment) {

				if ($counter != 0) {
					$ids .= ','.$attachment->ID;
				}
				else {
					$ids .= $attachment->ID;
				}
				$counter++;
			}
		}
		return $ids;
}

 

And now we can use the following code in our loop:

$attachment_ids = get_random_gallery_images();
echo do_shortcode('[ gallery columns="4" include="'.$attachment_ids.'" link="file" ]');

The result is a loop with posts containing galleries and displaying 4 images from the gallery.

Note: The above code has some extra whitespace between the [], because WordPress interprets the code and it won’t show.

Hope this helps!

Share