Using WordPress ‘file_is_displayable_image()’ PHP function

The file_is_displayable_image() WordPress PHP function checks if a file is suitable for displaying within a web page.

Usage

Let’s say you have an image with the file path /uploads/2023/05/my-image.jpg. You can use this function to check if this file is suitable for displaying.

$path = '/uploads/2023/05/my-image.jpg';
$is_displayable = file_is_displayable_image($path);

In this case, the $is_displayable variable will be a boolean that tells you whether the file can be displayed or not.

Parameters

  • $path (string): The file path that you want to test.

More information

See WordPress Developer Resources: file_is_displayable_image()

Examples

Checking if a JPEG image is displayable

Here, we are checking if a JPEG image can be displayed.

$path = '/uploads/2023/05/image.jpg';
$is_displayable = file_is_displayable_image($path);

Checking if a PNG image is displayable

This time, we are checking a PNG image.

$path = '/uploads/2023/05/image.png';
$is_displayable = file_is_displayable_image($path);

Checking if a GIF image is displayable

In this example, we are checking a GIF file.

$path = '/uploads/2023/05/image.gif';
$is_displayable = file_is_displayable_image($path);

Checking if a non-image file is displayable

This code shows what happens when you check a non-image file, like a text file.

$path = '/uploads/2023/05/textfile.txt';
$is_displayable = file_is_displayable_image($path);

Checking if a non-existent file is displayable

Finally, this code shows what happens when the function checks a file that doesn’t exist.

$path = '/uploads/2023/05/nonexistent.jpg';
$is_displayable = file_is_displayable_image($path);

In each of these examples, the $is_displayable variable will be a boolean value. If the file is suitable for display, it will be true; otherwise, it will be false.