How to Get Featured Image of a Post in WordPress

In this Blog post we will be discussing different ways of how to get featured image of a post in WordPress. While doing customizations, making custom templates or working with custom post types you will be needing to get access to WordPress featured image. so let’s get started.

Here is guide of how to get access to post id.

1. Retrieving the Featured Image Using WordPress Functions

WordPress Provides built-in functions to get the featured image of a post such as get_post_thumbnail_id() and wp_get_attachment_image_src(): The first parameter of this is the post ID and the second parameter of this function will the image size. The size can be thumbnail, medium or full etc.

<?php if (has_post_thumbnail( $post->ID ) ): ?>
  <?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?>
  <div id="custom-bg" style="background-image: url('<?php echo $image[0]; ?>')">

  </div>
<?php endif; ?>

If you want JUST the source, and not an array with other information:

<?php $url = wp_get_attachment_url( get_post_thumbnail_id($post->ID), 'thumbnail' ); ?>
<img src="<?php echo $url ?>" />

if you are working in a loop you can use the_post_thumbnail function.

<?php the_post_thumbnail('single-post-thumbnail'); ?>

here you can also use get_the_post_thumbnail_url like this below

<?php $img = get_the_post_thumbnail_url($postID, 'post-thumbnail'); ?>

here is another function get_the_post_thumbnail you can use to get the featured image URL

<?php echo get_the_post_thumbnail($post_id, 'thumbnail', array('class' => 'alignleft')); ?>

You can also get it from post_meta like this:

<?php echo get_post_meta($post->ID, 'featured_image', true); ?>

2. Retrieving Featured Image Metadata

WordPress provides metadata for featured images including alternative text and caption. Developers can access this metadata using wp_get_attachment_metadata():

$attachment_metadata = wp_get_attachment_metadata( $post_thumbnail_id );
$alt_text = $attachment_metadata['image_meta']['title']; // Get alternative text
$caption = $attachment_metadata['image_meta']['caption']; // Get caption

In conclusion mastering the code for retrieving and manipulating featured images in WordPress opens up a world of possibilities for developers. By understanding the core functions, leveraging metadata, employing custom queries and harnessing hooks and filters the developers can craft bespoke solutions that elevate the visual impact of WordPress websites. Whether you’re building themes, plugins or custom functionality. Delving into the featured image code unlocks a realm of creative potential in WordPress development.

Leave a Reply

Your email address will not be published. Required fields are marked *