How to Get the Source of the Featured Image in WordPress

Home » Snippets » How to Get the Source of the Featured Image in WordPress
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

Do you find yourself in the position of needing to retrieve the source URL of the featured image on your WordPress site? Whether it’s for customization purposes or for displaying the image in a different location, having quick and easy access to the featured image source can be a useful skill to have. In this article, we’ll guide you through the process of retrieving the source URL of the featured image in WordPress, so you can make the most out of your website’s visual content.

					function wpturbo_get_featured_image_src($size = 'full') {
    $featured_image = wp_get_attachment_image_src(get_post_thumbnail_id(), $size);
    return $featured_image[0];
}
				

The code snippet provided demonstrates how to retrieve the source (URL) of the featured image in WordPress. It defines a function called wpturbo_get_featured_image_src that takes an optional argument $size to specify the size of the image, with 'full' being the default size.

Within the function, we make use of the wp_get_attachment_image_src function, which retrieves an array of information about the image attachment specified by get_post_thumbnail_id(). This function returns an array in the format [url, width, height, is_intermediate], and we only need the URL of the image, hence we access it using $featured_image[0].

The next line returns the image URL as the output of the function.

To use this function, you can simply call wpturbo_get_featured_image_src() and optionally pass the desired size as an argument. For example, wpturbo_get_featured_image_src('thumbnail') will provide the source URL of the thumbnail-size featured image.

This code can be particularly useful when you need to display the featured image source in a custom WordPress theme or plugin, or when you want to perform additional manipulation or processing with the image URL.

Register an account to save your snippets or go Pro to get more features.