Thord Daniel Hedengren - Smashing WordPress_ Beyond the Blog-Wiley (2014)

(avery) #1

146 PART II • Designing and Developing WordPress Themes


Just enabling the Featured Image box won’t make the featured images show up in your theme,
however. Using the_post_thumbnail() within the loop, you can output the image. If you
need additional control, you can combine it with the conditional tag
has_post_thumbnail().

<?php the_post_thumbnail(); ?>

Used like this, the_post_thumbnail() will output the thumbnail version of the image.
By passing any of the parameters thumbnail, medium, or large, you’ll get those versions
instead. If you added an image size, such as the previous top-feature one, you can pass
that as well. You can also pass an array with a custom resolution, like so, which will then scale
from the next largest image size:

the_post_thumbnail( array( 320, 130) );

Featured images are often used on the top of posts or in headlines to make the post more
appealing. For some additional control, you can pass a CSS class to the featured image to get
some more styling options:

the_post_thumbnail( 'medium', array( 'class' => 'headline' ) );

This will add the class headline to the img tag outputted by the_post_thumbnail().
By default, you’ll get the wp-post-image class, as well as the class attachment-X, where
X is the chosen version of the image (for example, attachment-large).

If you’re not entirely sure that every post has a featured image attached to it, you should do a
conditional check first. Something like this will do just fine:

<?php // Is there a featured image?
if ( has_post_thumbnail() ) {

// There was; let's use it!
the_post_thumbnail();

}
// All done
?>

CUSTOM MENUS
You might recognize custom menus from the example in Chapter 4, but for clarity’s sake, I’ll
revisit them quickly. Adding support for menus is really simple. Start by adding a menu area
for your theme, called Smashing Menu in this example. Do this in functions.php:

// Register menus
register_nav_menus( array(
'smashing-menu' => 'Smashing Menu',
) );
Free download pdf