So the other day I had to implement a thumbnail of the featured image in WordPress. Little did I know about a little feature in WordPress called wp_get_image_editor, which is basically a tool that allows you to edit an image (resize and crop it), and save it as a new image.
So after a lot of trial and error I came up with the following code to generate and save a 120px thumbnail image of the featured image of a post:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
if (get_the_ID() && get_post_thumbnail_id(get_the_ID())) { $imageArr = wp_get_attachment_image_src( get_post_thumbnail_id(get_the_ID()), 'single-post-thumbnail'); $imageSrc = $imageArr[0]; $imagePath = realpath(str_replace(get_bloginfo('url'), '.', $imageSrc)); $name = basename($imagePath); $newImagePath = str_replace($name, 'thumb_' . $name, $imagePath); $newImageSrc = str_replace($name, 'thumb_' . $name, $imageSrc); if (!file_exists($newImagePath)) { $image = wp_get_image_editor($imagePath); if (!is_wp_error($image)) { $image->resize(120, 120, true); $image->save($newImagePath); } } ?> <img width="120" height="120" src="<?php echo $newImageSrc; ?>" class="attachment-120x120 wp-post-image"/> <?php } |
Of course, placing this in a template isn’t very DRY, so I refactored it to this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
/** * Generate a thumbnail * * @param int $attachmentId The ID of the attachment (get_post_thumbnail_id) * @param int $size The size of the image * @return mixed The src of the new image */ function generateThumbnail($attachmentId, $size = 100) { $imageArr = wp_get_attachment_image_src($attachmentId, 'single-post-thumbnail'); $imageSrc = $imageArr[0]; $imagePath = realpath(str_replace(get_bloginfo('url'), '.', $imageSrc)); $name = basename($imagePath); $newImagePath = str_replace($name, 'thumb_' . $size . '_' . $name, $imagePath); $newImageSrc = str_replace($name, 'thumb_' . $size . '_' . $name, $imageSrc); if (!file_exists($newImagePath)) { $image = wp_get_image_editor($imagePath); if (!is_wp_error($image)) { $image->resize($size, $size, true); $image->save($newImagePath); } } return $newImageSrc; } |
In your template you can use it (for example) like this:
1 2 |
<?php $thumbnail = generateThumbnail(get_post_thumbnail_id(), 70); ?> <img src="<?php echo $thumbnail; ?>" alt="foo bar" width="70" height="70" /> |
So there you have it, enjoy!
Visitors give this article an average rating of 4.2 out of 5.
How would you rate this article?
★ ★ ★ ★ ★