How to get Post Thumbnail URL with Custom Size

4.0714285714286 from 5
from 14 user
(Rate this post)
How to get Post Thumbnail URL with Custom Size

WordPress generates different sizes for each uploaded image in the admin panel. Also, WordPress developers can register custom sizes for future generating. If you are interested in fetching a post's thumbnail URL in custom size, read this article. I'm going to try registering new thumbnail sizes and retrieving thumbnails for each registered size.

Register a custom size for images in WordPress

Registering a custom image size in WordPress is easy task to do.

To register a new image size, we are going to use the add_image_size function inside functions.php or a custom plugin:

$sizeName = "100-100";
$width = 100;
$height = 100;
$crop = true;

add_image_size($sizeName, $width, $height, $crop);

Read more about registering a custom size for images, in my articles:

How to Register a Custom Image Size in WordPress? (+Example)

Retrieve thumbnail URL with desired size

After registering a desired size for images, you can retrieve uploaded images in registered size.

You only need to use the name of thumbnail size you registered in get_the_post_thumbnail_url function:

$postId = 1; //select post by id
$sizeName = "100-100"; //registered name in previous example!

$thumbnailUrl = get_the_post_thumbnail_url($postId, $sizeName);

Retrieve WordPress default thumbnail sizes

WordPress has a few default image sizes: thumbnail, medium, medium_large, and large.

Use each one of these default sizes in get_the_post_thumbnail_url function to get the URL you need.

$postId = 1; //select post by id
$thumbnailUrl = get_the_post_thumbnail_url($postId, "thumbnail");
$mediumUrl = get_the_post_thumbnail_url($postId, "medium");
$mediumLargeUrl = get_the_post_thumbnail_url($postId, "medium_large");
$largeUrl = get_the_post_thumbnail_url($postId, "large");

Note: if thumbnails are not generating (check the file server to find out), check if GD is enable in your PHP.

To do that, open php.ini file in the server and search for extension=gd in the file. If you see ; character in the begining of it’s declaration line, remove the ; to enable GD.

Then restart the web server.

What do you think about "How to get Post Thumbnail URL with Custom Size"?

Your rating submit was successfull.

Your rating submit was not successfull.

Menu