Problem
When uploading an image through the WordPress media library, the system automatically generates several versions of the image in various resolutions. This ensures high performance by displaying the most appropriate image size for different contexts.
As a result, files like the following are created:
uploads/file.webp
uploads/file-scaled.webp
uploads/file-100x100.webp
uploads/file-1024x1024.webp
It may seem that the WordPress API offers a straightforward way to retrieve the URL of an image at a desired size using its ID. However, there are some situations:
- Sometimes, you need to use the URL of a scaled-down version for display purposes while also obtaining the URL of the original file, e.g., for use in JavaScript to show the image in a media viewer.
- If you upload a very high-resolution image, attempting to get the original file URL using WordPress’ built-in functions may instead return the
scaled
version.
To address these issues, I’ve written a small function that uses a regular expression to modify the URL of any attachment version, transforming it into the URL of the original file.
Function
Just pass the URL of any version of the image to the function and it will return the URL of the original file.
/** * Retrieves the full size attachment image URL. * * @param string $image_url Scaled image URL. * @return string Original image URL. */ function ym_get_full_image_url( string $image_url ) : string { return preg_replace( '/-(\d+x\d+|scaled)(\.\w+)$/', '$2', $image_url ); }
Regular Expression Explained
Let’s break down the regular expression used in the function:
-(\d+x\d+|scaled)(\.\w+)$
-(\d+x\d+|scaled)
- Matches a segment starting with a hyphen (
-
). - The segment contains either:
- A pattern like
dxd
(e.g.,100x100
), whered
is any number of digits, andx
is the literal characterx
. - Or the string
scaled
.
- A pattern like
- Matches a segment starting with a hyphen (
(\.\w+)$
- Ensures the pattern ends with a file extension.
\.
matches a literal dot (.
).\w+
matches any sequence of letters, corresponding to the file extension.$
signifies the end of the string.
- Parentheses are used to separate these two parts into groups. The entire match is then replaced with the content of the second group (
$2
), which is the file extension.
Conclusion
This function and its regular expression reliably retrieve the URL of the original attachment file, avoiding issues like accidental pattern matches in filenames or similar problems.