
I was recently customizing a photo theme for a friend and set up Qiniu Cloud Storage for it. We wanted the thumbnails to support external URL images. While Qiniu does have an API for fetching images at different sizes, that felt like overkill for a personal blog. Here’s the simplest method — no API calls needed, and it works for all external images in WordPress, even without Qiniu.
Features of this method:
- Supports manually uploaded thumbnails
- Supports external URL thumbnails
- If the post contains images, uses the first image as the thumbnail
- If the post has no images, uses a default image
The solution leverages WordPress’s Custom Fields functionality.
$postImageUrl = get_post_meta($post->ID, 'thumbnail', true); // Set custom field name to "thumbnail"
- Add the following code to your
functions.phpfile:
// Thumbnail retrieval
add_theme_support( 'post-thumbnails' );
set_post_thumbnail_size( 262, 114 ,true ); // Set thumbnail dimensions
function dm_the_thumbnail() {
global $post;
$postImageUrl = get_post_meta($post->ID, 'thumbnail', true); // Set custom field name to "thumbnail"
// Check if the post has a featured image set; if so, display it directly
if ( has_post_thumbnail() ) {
echo '<span class="work-thumbnail">';
the_post_thumbnail();
echo '</span>';
} elseif ($postImageUrl) {
echo '<span class="work-thumbnail"><img alt="" src="'.$postImageUrl.'" /></span>';
} else { // If no featured image is set, check if the post contains any images
$content = $post->post_content;
preg_match_all('/<img.?(?: |\t|\r|\n)?src=[\'"]?(.+?)[\'"]?(?:(?: |\t|\r|\n)+.?)?>/sim', $content, $strResult, PREG_PATTERN_ORDER);
$n = count($strResult[1]);
if($n > 0){ // If the post contains images, use the first one as the thumbnail
echo '<span class="work-thumbnail"><img alt="" src="'.$strResult[1][0].'" /></span>';
}else { // If the post has no images, use the default image
echo '<span class="work-thumbnail"><img alt="" src="'.get_bloginfo('template_url').'/images/thumbnail.jpg" /></span>';
}
}
}
-
After completing these steps, click “Screen Options” in the top-right corner of the admin panel and enable the Custom Fields checkbox.
-
Download the timthumb.php file, place it in your theme’s root directory, then adjust the styles accordingly. Feel free to modify the HTML structure and class names in the code to suit your theme.