Add Featured Image Before Content In Any Theme

I’ve already written about adding images before and after titles in Genesis but how about for other themes?

In this post, i’ll give you the code which works in any theme.

image before content

The code uses the_content filter built into WordPress, adds the featured image you add on your Edit Post screen and then returns the content after the image on single posts.

Please copy ALL the code from the view raw link in the Gist and paste it at the end of your child themes functions.php file using a text editor like Notepad++

You can extend further and set an image size as well as add a class to add some margin between the image and your content which you can do in the PHP code.

Set Image Size

You can extend the code further and add both a size and class.

The above code includes the full size determined by your Settings > Media. You can change this size to any size included in your Media settings like:

  • thumbnail
  • medium
  • large
  • full

Otherwise, you can add custom image sizes in your functions file specifically for your featured image.

//* Add new image sizes
add_image_size( 'featured-image', 700, 350, TRUE );

Here’s an example of using a custom size in this code. Simply add your custom size to this line of code like this:

Before:

$img = get_the_post_thumbnail($post_id, 'thumbnail', array('class' => 'alignright'));

After:

$img = get_the_post_thumbnail($post_id, 'featured-image', array('class' => 'post-thumbnail'));

Some of the examples above include the alignright class which can be changed to a new class or an existing class your theme includes.

Featured Image Class

wrap text around image

Here’s an example of adding a new class in this code. Simply add the new class to this line of code like this:

Before:

$img = get_the_post_thumbnail($post_id, 'thumbnail', array('class' => 'alignright'));

After:

$img = get_the_post_thumbnail($post_id, 'full', array('class' => 'image-before-content'));

Then you can add padding and style your featured image in your child themes style.css file. Here’s an example:

.image-before-content {
border: 5px solid pink;
margin-bottom: 50px;
}

And here’s a screenshot showing you the result of using the above class and CSS:

add margin and style image before content

Link Featured Image To Posts Permalink

This code links the featured image to the posts permalink on each page.

Join 5000+ Followers

Get The Latest Free & Premium Tutorials Delivered The Second They’re Published.