Blog / WordPress/ How to Display Multiple Post Images as Thumbnails in WordPress

How to Display Multiple Post Images as Thumbnails in WordPress

WordPress成功调用多张文章缩略图的教程

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_images variable 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

  1. Add the function to your theme's functions.php.
  2. 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_content directly.
  • Style the thumbnails by adding CSS rules for the .preview-img class 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.

Post a Comment

Your email will not be published. Required fields are marked with *.