get_the_post_thumbnail_url with an unregistered size

The official code reference for get_the_post_thumbnail_url states:

$size (string|array) (Optional) Registered image size to retrieve the source for or a flat array of height and width dimensions.

(emphasis mine).

I’m using the following parameters:

$img_url = get_the_post_thumbnail_url(get_the_ID(), array('300' , '170'));

But it doesn’t return the size I want.

The registered image sizes are 150 x 150, 300 x 300 and 1024 x 1024.

Solutions Collecting From Web of "get_the_post_thumbnail_url with an unregistered size"

WordPress does not create any thumbnail on the fly. If you try to fetch a size that doesn’t exist, either the closest size or the full size image will be retrieved.

The closest solution you can try is to fetch a size larger than what you want, and then size it down via CSS and crop it.

Let’s say the registered sizes are 50 x 150, 300 x 300 and 1024 x 1024, but you need a 300x177 image. Fetch the 300x300 one, and then clip it using CSS:

#my-div img {
    position: absolute;
    clip: rect( 0px, 300px, 177px, 0px );