WordPress Code Snippets

A fresh mix of code snippets and tutorials

Set attachment as featured image

100

Here’s how to set the first attachment as the featured image for posts in WordPress. This is useful for User Submitted Posts, which attaches uploaded images to each submitted post.

Before implementing this technique, it helps to publish a few test posts that each have at least one attached image. Also, remember to make backups before modifying any files.

Step 1: Enable Featured Images

Add the following code to functions.php:

This snippet does two things: 1) adds theme support for featured images, and 2) sets a reasonable size for the featured images (which were once known as “post thumbnails”). Feel free to adjust the size as needed.

Step 2: Set & Display

With some test posts in place and theme support for featured images, it’s time to bring it all together in your theme’s single.php file (for example) with the following code placed anywhere in the loop:

With this code: if the post has a featured image it’s displayed, otherwise we set the first attachment as the “post thumbnail” (aka featured image) and then display it. Notice that we’re using a variety of related WP functions:

Using the Codex as a guide, it’s possible to customize this technique in a variety of ways.

Alternate method

If you would rather not mess with adding code to the loop, here is an alternate method for setting the featured image via the functions.php file:

This code essentially operates the same way as the previous technique, with the exception that we’re filtering the_content while using get_children() instead of get_posts(). Customize as needed and have fun!

Update! You may also be interested in my technique for displaying all images attached to a post »

Learn more

Digging into WordPress