Check if a Remote Image File Exists in WordPress

June 27, 2018

If you want to check if a remote image file exists on a WordPress site but don’t necessarily want to fetch or download that file, this lightweight helper function can be used for that purpose:

* Check if a remote image file exists.
* @param string $url The url to the remote image.
* @return bool Whether the remote image exists.
function km_remote_image_file_exists( $url ) {
$response = wp_remote_head( $url );
return 200 === wp_remote_retrieve_response_code( $response );

Example Usage

It can be used like this:

$image_url = '';
if ( km_remote_image_file_exists( $url ) ) {
echo 'The remote image exists! Hooray!';
} else {
echo 'The remote image does not exist. Boooooo.';

Kellen Mace

Written by Kellen Mace, who lives in Rochester Hills, MI and builds cool stuff on the web. About Kellen // Follow him on Twitter →