How to add featured image in WordPress custom output

I’m working on a WordPress site and I have this code that displays course information:

$content .= '<div class="course-highlight" '.$styling.'>';
$content .= '<h2><a href="' . get_permalink(). '">' . get_the_title(). '</a></h2>';
$content .= '<div class="description">' . custom_excerpt_limit(70). '</div>';
$content .= '<a class="course-link" href="' . get_permalink(). '">' . __('Read More', 'my-theme'). ' <i class="fa fa-arrow-right"></i></a>';

I want to include a thumbnail image in this output but I’m not sure what function to use. What’s the best way to add the featured image or post thumbnail to this code? I tried looking at the WordPress documentation but there are several different functions and I’m confused about which one would work best for my situation.

you can also use wp_get_attachment_image_src() if you want full control over the HTML. it returns just the image URL, so you can create your own img tag with custom attributes and classes that fit your theme better than wordpress’s default markup.

Use get_the_post_thumbnail() - it’s the most flexible option since it returns the complete img tag you can drop straight into your content string. Just add it after your h2 tag:

$content .= '<div class="course-highlight" '.$styling.'>';
$content .= '<h2><a href="' . get_permalink(). '">' . get_the_title(). '</a></h2>';
$content .= get_the_post_thumbnail(get_the_ID(), 'medium');
$content .= '<div class="description">' . custom_excerpt_limit(70). '</div>';

The second parameter sets image size - ‘thumbnail’, ‘medium’, ‘large’, or ‘full’. I’d go with ‘medium’ for course highlights - good balance between quality and loading speed. Don’t forget to check if the post has a featured image with has_post_thumbnail() first, otherwise you’ll get empty img tags.

I always wrap the featured image in a conditional check so posts without thumbnails don’t break the layout. Here’s what works for me:

$content .= '<div class="course-highlight" '.$styling.'>';
$content .= '<h2><a href="' . get_permalink(). '">' . get_the_title(). '</a></h2>';
if (has_post_thumbnail()) {
    $content .= '<div class="course-image">' . get_the_post_thumbnail(get_the_ID(), 'medium') . '</div>';
}
$content .= '<div class="description">' . custom_excerpt_limit(70). '</div>';

Wrapping it in a div with a class gives you better styling control. I put the image right after the title but before the description - creates a nice visual hierarchy. Also throw some CSS on there to make it responsive with max-width: 100% so it doesn’t break on mobile.