This tutorial explains how to display multiple images from a WordPress post as thumbnails in your theme, a common request for galleries or featured image alternatives.
Implementation Code
Add the following PHP function to your theme's functions.php file:
/**
* Display multiple post images as thumbnails.
*/
function preview_img($soContent) {
// Match all img tags in the post content
$soImages = '/<img[^>]+\/?>/i';
preg_match_all($soImages, $soContent, $thePics);
$allPics = count($thePics[0]);
if ($allPics > 0) {
$count = 0;
$max_images = 5; // Adjust maximum number of images to display
foreach ($thePics[0] as $v) {
if ($count >= $max_images) {
break;
}
// Output each image wrapped in a span for styling
echo '<span class="preview-img">' . $v . '</span>';
$count++;
}
}
}
Code Explanation
- Regular Expression: Correctly matches all
<img>tags (self-closing or not) within the post content. - Image Count: Uses
count($thePics[0])to get the actual number of matched images. - Limit Control: The
$max_imagesvariable lets you easily set how many thumbnails to display. - Output: Each image is wrapped in a
<span class="preview-img">for CSS styling.
How to Use
- Add the function to your theme's
functions.php. - Call it within your post loop where you want thumbnails to appear:
<?php preview_img(get_the_content()); ?>
Important Notes
- Use
get_the_content()for better compatibility and security than accessing$post->post_contentdirectly. - Style the thumbnails by adding CSS rules for the
.preview-imgclass in your theme's stylesheet. - This method extracts all
<img>tags from the post content. Complex or external images may require regex adjustments. - Always use a child theme or backup your files before editing.