Reputation: 59
I'm using the following code to display a featured image in WordPress. It's working correctly, but I am struggling with get_the_title()
to display the title of the post within the image and have that adjust correctly when being responsive.
echo '<img src="'.wp_get_attachment_url( get_post_thumbnail_id() ).'" style="width:100%; height:auto;">';
Upvotes: 0
Views: 91
Reputation: 943
You can make the image as a background in a div and place the title inside.
// you can use get_the_ID() or $post->ID to get the ID of the post
$featured_img_url = get_the_post_thumbnail_url($post->ID, 'full');
<div class="wrapper" style="background-image: url(<?php echo $featured_img_url;?>);">
<h2 class="the-title"><?php echo the_title(); ?></h2>
</div>
// Add this to your css
.wrapper{
position: relative;
height: 200px;
width: 200px;
background-position: center;
background-size: cover;
background-repeat: no-repeat;
}
// This will center the text inside
.the-title{
position: absolute;
top: 0;
bottom: 0;
text-align: center;
}
Upvotes: 1