0
0
Wordpressframework~5 mins

Featured images in Wordpress

Choose your learning style9 modes available
Introduction

Featured images let you add a main picture to your posts or pages. This makes your content look nice and helps readers understand what it is about quickly.

When you want to show a main picture for a blog post to attract readers.
When creating a portfolio and you want each project to have a thumbnail image.
When making a news site and you want each article to have a headline image.
When designing a homepage that shows recent posts with images.
When you want to improve how your posts look when shared on social media.
Syntax
Wordpress
<?php set_post_thumbnail( $post_id, $thumbnail_id ); ?>
Use set_post_thumbnail to assign a featured image to a post programmatically.
The $post_id is the ID of the post, and $thumbnail_id is the ID of the image attachment.
Examples
This code checks if the current post has a featured image and then displays it.
Wordpress
<?php if ( has_post_thumbnail() ) {
  the_post_thumbnail();
} ?>
This sets the featured image with ID 123 for the post with ID 42.
Wordpress
<?php set_post_thumbnail( 42, 123 ); ?>
This displays the featured image in the 'medium' size.
Wordpress
<?php the_post_thumbnail( 'medium' ); ?>
Sample Program

This WordPress template code loops through posts. For each post, it shows the featured image in large size with an alt text for accessibility. If no featured image is set, it shows a message. Then it displays the post title and content.

Wordpress
<?php
// Template part to show featured image in a post
if ( have_posts() ) {
  while ( have_posts() ) {
    the_post();
    if ( has_post_thumbnail() ) {
      the_post_thumbnail( 'large', ['alt' => get_the_title()] );
    } else {
      echo '<p>No featured image set.</p>';
    }
    the_title( '<h2>', '</h2>' );
    the_content();
  }
}
?>
OutputSuccess
Important Notes

Always add alt text to images for accessibility.

Featured images improve how your posts look on social media and search engines.

You can set featured images in the WordPress editor or programmatically with code.

Summary

Featured images add a main picture to posts or pages.

Use has_post_thumbnail() to check and the_post_thumbnail() to display it.

They help make your site more attractive and accessible.