Blog / WordPress/ Generating WordPress Post Thumbnails: TimThumb (Historical Method) and Modern Alternatives

Generating WordPress Post Thumbnails: TimThumb (Historical Method) and Modern Alternatives

WordPress 使用 TimThumb 生成文章缩略图(历史方法与现代替代方案)

Introduction: Why Custom Thumbnails?

By default, WordPress generates multiple thumbnail sizes (thumbnail, medium, large) for every uploaded image. If your theme or plugins don't use all these sizes, server space gets wasted with unused files. Historically, developers used a script called timthumb.php to generate thumbnails dynamically on demand.

Important Notes About TimThumb

Warning: TimThumb is an outdated and insecure historical solution.

  • Requires GD Library: Needs PHP's GD image processing extension.
  • Server Resource Intensive: Processes images on each request, consuming CPU and memory.
  • No External Image Support: By default, only processes images hosted on your own server.
  • Known Security Vulnerabilities: Has had serious security flaws that could lead to server compromise.
  • Project Abandoned: No longer maintained; using it means accepting potential security risks.

Given these risks, using TimThumb on modern WordPress sites is strongly discouraged. This document first explains its historical usage, then focuses on safer, more efficient modern alternatives.

Step 1: Disable Default WordPress Thumbnails

To save space, you can prevent WordPress from generating unneeded image sizes. In your WordPress admin, go to Settings → Media.

Set the width and height for "Thumbnail size", "Medium size", and "Large size" to 0 or leave them blank. After saving, newly uploaded images will keep only the original file.

Note: This setting only affects newly uploaded images. Existing thumbnail files must be cleaned up manually.

Historical TimThumb Deployment Method

1. Download and Deploy

  1. Download the timthumb.php file (get its final version from a reliable source).
  2. Upload it to your active WordPress theme folder.
  3. Create a new folder named cache in the same theme folder to store TimThumb's cached images. Set its permissions to 755 or 777 (depending on your server).

2. Function to Get Post Thumbnail URL

Add this function to your theme's functions.php to get a post's thumbnail URL (prioritizes custom field, then featured image, then first image from content).

// WordPress function to get post thumbnail URL
function post_thumbnail_src() {
    global $post;
    $post_thumbnail_src = '';

    // 1. Check custom field 'thumbnail'
    if ($values = get_post_custom_values("thumbnail")) {
        $post_thumbnail_src = $values[0];
    }
    // 2. Check for featured image
    elseif (has_post_thumbnail()) {
        $thumbnail_src = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'full');
        $post_thumbnail_src = $thumbnail_src[0];
    }
    // 3. Extract first image from post content
    else {
        ob_start();
        ob_end_clean();
        $output = preg_match_all('/<img.+src=['"]([^'"]+)['"].*>/i', $post->post_content, $matches);
        if (!empty($matches[1][0])) {
            $post_thumbnail_src = $matches[1][0];
        }
        // 4. Fallback to default image
        if (empty($post_thumbnail_src)) {
            $post_thumbnail_src = get_template_directory_uri() . "/images/no-image.jpg";
        }
    }
    return $post_thumbnail_src;
}

3. Template Call

Where you need to display the thumbnail (e.g., index.php, archive.php), insert:

<img src="<?php echo get_template_directory_uri(); ?>/timthumb.php?src=<?php echo post_thumbnail_src(); ?>&h=150&w=200&zc=1" alt="<?php the_title(); ?>" />

Parameter explanation:

  • h: Thumbnail height (pixels).
  • w: Thumbnail width (pixels).
  • zc: Zoom crop mode. 1 for scale and crop to exact size; 0 for proportional scaling (may leave padding).

4. Security Patch (Historical)

Since TimThumb's vulnerabilities often involved external domain whitelists, an old patch suggested: In timthumb.php, find the $allowedSites array definition and delete or comment it out to block external images and reduce risk.

// External domain whitelist (delete or comment out to disable)
// $allowedSites = array (
//        'flickr.com',
//        'picasa.com',
//        'blogger.com',
//        'wordpress.com',
//        'img.youtube.com',
// );

Modern WordPress Thumbnail Best Practices

Given TimThumb's issues, here are better modern solutions:

Option 1: Use WordPress Core & Image Optimization Plugins

  1. Use default thumbnails wisely: In Settings → Media, define only the sizes you actually need (e.g., for post lists, related posts).
  2. Use professional optimization plugins: Like ShortPixel, Imagify, or EWWW Image Optimizer. They compress images, clean unused thumbnails, save space, and improve performance.

Option 2: Use Modern, Secure Scripts or CDN

  • CDN dynamic image processing: Services like Cloudinary, Imgix, or Akamai Image Manager can crop, scale, and optimize images via URL parameters, offloading work from your server.
  • Use maintained libraries: If server-side processing is necessary, consider integrating a modern, actively maintained library like Intervention Image (based on PHP GD or Imagick) with secure wrappers.

Option 3: Theme Development Recommendations

For theme developers, the best approach is:

  1. Use add_image_size() in functions.php to register exact image sizes your theme needs.
  2. In templates, use the_post_thumbnail('your-registered-size').
  3. Implement responsive images with wp_get_attachment_image_srcset().
  4. Clean unused image sizes regularly with plugins like Force Regenerate Thumbnails or custom code.

Summary: TimThumb is a historical solution no longer suitable. Prioritize WordPress native features with optimization plugins or professional cloud image services for better performance, security, and maintainability.

Post a Comment

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