Featured Image Meta

meta-display

I’ve built a couple themes where I’ve needed to give users more control over how the featured image is displayed for individual posts. The obvious place to put these options are in the thumbnail metabox itself.

Display Thumbnail Landscape

meta-banner

In this theme the default display of the thumbnails is a cropped to a square next to the title. But if the user had a large landscape image, they could choose to display it full width instead.

Option to Display Featured Image in Post Automatically

meta-display

In this theme the featured image is used as a thumbnail on portfolio archive pages, but it is also displayed full size on the portfolio post types. This option gives users the option to use a different image in the actual post if they prefer.

Add the Option

Adding the option is fairly simple, you’ll just need to hook into the admin_post_thumbnail_html filter:

/* Add a checkbox to the featured image metabox */

add_filter( 'admin_post_thumbnail_html', 'theme_featured_image_meta');

function theme_featured_image_meta( $content ) {
	global $post;
	$text = __( "Don't display image on post.", 'textdomain' );
	$id = 'hide_featured_image';
	$value = esc_attr( get_post_meta( $post->ID, $id, true ) );
    $label = '<label for="' . $id . '" class="selectit"><input name="' . $id . '" type="checkbox" id="' . $id . '" value="' . $value . ' "'. checked( $value, 1, false) .'> ' . $text .'</label>';
    return $content .= $label;
}

Sanitize and Save the Option

This option will need to be sanitized and saved when the post is updated- like any other custom field in a metabox.

This is a longer topic than I want to cover in this short post, but if you need a tutorial on how to do that I’d recommend the one on Smashing Magazine by Justin Tadlock.

Credits

The thumbnail images above are from Alexander S. Kunz Photography.

About Devin

I'm a WordPress developer based in Austin, Texas. Follow my projects on GitHub, or more general WordPress ramblings as @devinsays on twitter.

10 Responses

  1. This is pretty neat! I can picture something similar being very useful in conjunction with a plugin that adds Twitter or Opengraph meta tags. It makes a lot of sense to use the featured image in these cases, but what if the use does not want the featured image to be displayed in the theme? Neat solution :)

  2. Didier Sajno

    I’ve been looking for that particular feature, however not being a coder, I find it hard to follow the instructions from Justin Tadlock’s tute.
    – I’ve copied/pasted the above code into functions.php

    Now I get the option under the featured image thumbnail but it doesn’t do anything, I guess that’s where the sanitise/save comes in. But I couldn’t resolve this… can you help?

Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>