How Do I Fetch an Image in WordPress?

In WordPress, you can fetch an image from a URL or from a directory. To fetch an image from a URL, use the wp_get_image() function. To fetch an image from a directory, use the wp_get_images() function. The following example fetches the image “sample.

jpg” from the URL “http://example.com/images/sample.jpg” into the current WordPress image directory:.

$path = ‘http://example.com/images/'; $file = ‘sample.jpg'; $result = wp_get_image($path, $file); if ($result === false) { echo “Can’t find image ‘$file’ in $path”; } else { echo “Fetched image ‘$file’ from $path”; }

The wp_get_images() function behaves identically to the wp_get_image() function, except that it accepts a path instead of a URL. The path must be a valid WordPress path.

The following example fetches the images “logo.png” and “user.png” from the directory “/images” on the server:.

$path = ‘/images'; $file = ‘logo.png'; $result = wp_get_images($path, $file); if ($result === false) { echo “Can’t find image ‘$file’ in ‘/images'; } else { echo “Fetched image ‘$file’ from ‘/images'; }

The wp_get_image() and wp_get_images() functions both return an image object. The image object has the following properties:

width: The width of the image in pixels.

height: The height of the image in pixels.

src: The URL or directory path where the image is located.

alt: The alt text of the image.

The src and alt properties are optional. If they are not specified, the image is fetched from the URL given in the src property.

If the src property is a directory path, the images in the directory are used.

The src and alt properties are automatically set to the empty string if the image cannot be found. If the src or alt property is set to an empty string, the image is not fetched.