Browse Site

Add a Featured Image to your WordPress Theme

If your theme doesn’t make use of WordPress’s featured image out of the box, then all you need to do is to add the following lines of code to your functions file;

add_theme_support( 'post-thumbnails' );
add_filter( 'the_content', insert_featured_image, 20 );
function insert_featured_image( $content ) 
	global $post;

	$url = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
	if (strlen($url) > 0)
		$img = '<img src="'.$url.'" alt="'.$post->post_title.'" title="'.$post->post_title.'" class="attachment-post-single wp-post-image alignright" />';
		$content = preg_replace( "/<p>/", "<p>".$img, $content, 1 );
	return $content;

The code above will add this to all pages and posts but you can add either of the following lines to narrow it down to only being used on one or the other.

// featured images on pages only:
add_theme_support( 'post-thumbnails', array( 'page' ) );

// featured images on posts only:
add_theme_support( 'post-thumbnails', array( 'post' ) );

What does this code do? If you look through the first code island, above, we are adding a filter to run the insert_featured_image function whenever “the_content”, used by WordPress for page / post content, is called. Then we’re seeing whether a featured image exists and, if so, we’re amending the output of $content to include the featured image.

The preg_replace regex pattern used here replaces the very first <p> tag in my content as this is where I’d like the featured image to appear but you could change it to use the first closing </p> tag or any other tag that you’d prefer.

This entry was posted in php, WordPress and tagged , .

Comments are closed.