There are numerous ways to display a great featured image on your site in the ever-changing world of WordPress. We’re pleased to present a completely accessible approach. You can ensure that your image not only captivates your audience but also remains accessible to those with visual impairments by utilising the alt tag from the media library. Get ready to create an inclusive and engaging visual experience for all your visitors!
Here’s the code we use:
// Get the featured image ID $featured_image_id = get_post_thumbnail_id(); // Get the featured image URL $featured_image_url = wp_get_attachment_image_src($featured_image_id, 'large'); // Get the alt text from the media library $alt_text = get_post_meta($featured_image_id, '_wp_attachment_image_alt', true); // Display the featured image echo '<img src="' . $featured_image_url . '" alt="' . $alt_text . '">';
Let’s have a look at what this code is doing in more detail:
$featured_image_id = get_post_thumbnail_id();: This line retrieves the ID of the featured image (also known as the post thumbnail) and stores it in the
$featured_image_url = wp_get_attachment_image_src($featured_image_id, 'large');: This line uses the featured image ID to obtain the URL of the featured image in its ‘large’ size. The URL is then stored in the
$alt_text = get_post_meta($featured_image_id, '_wp_attachment_image_alt', true);: This line retrieves the alt text of the featured image from the media library, using the image ID, and stores it in the
$alt_textvariable. Alt text is essential for accessibility as it provides a textual description of the image for visually impaired users.
echo '<img src="' . $featured_image_url . '" alt="' . $alt_text . '">';: This line displays the featured image using an
<img>HTML tag. The
srcattribute is set to the image URL, and the
altattribute is set to the alt text retrieved earlier. This ensures that the image is displayed with the appropriate accessibility information.
Wrapping it up
Finally, displaying a featured image in WordPress is important for both aesthetics and accessibility. You can create a visually appealing and inclusive experience for all of your visitors by following the approach outlined in this blog post. Always include the alt tag from the media library, as it is critical in making your content accessible to users with visual impairments. You’ll be well on your way to creating a website that captivates and engages a diverse audience if you use this simple yet effective method. Continue your exploration, and happy coding!