WordPress: Featured Images
When altering a theme in WordPress you may want to attach an image to an individual post or page for use as a custom banner or a post thumbnail. You can use the WordPress Featured Images to accomplish this and in many themes this is already built in. In some cases Post/Page Featured Image are not yet supported by the theme and must be declared.
First you must declare Post/Page Featured Image support by adding the following to your themes functions.php file:
1 |
add_theme_support( 'post-thumbnails' ); |
When the theme declares Post/Page Featured Image support you can see the Featured Image panel on the bottom right of the Page/Post edit screen:
When displaying the Featured Image in your theme you can use the following functions within the post loop. This will place an <img> tag with the src attribute pointing to your posts featured image.
To change the display size you can type one of the four predefined size names (thumbnail, medium, large, and full) as a sting into the first function parameter as shown below.
1 2 3 4 5 6 7 8 |
the_post_thumbnail(); // without parameter -> Thumbnail the_post_thumbnail('thumbnail'); // Thumbnail (default 150px x 150px max) the_post_thumbnail('medium'); // Medium resolution (default 300px x 300px max) the_post_thumbnail('large'); // Large resolution (default 640px x 640px max) the_post_thumbnail('full'); // Original image resolution (unmodified) the_post_thumbnail( array(100,100) ); // Other resolutions |
The ‘full’ size is the images original uploaded resolution. You can also pass an array where the first value is width and the second is height.
To retrieve a featured image from a Post or Page that you are not currently on you can use the following code passing the Post/Page ID as $post->ID.
1 2 3 |
<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?> <div id="custom-bg" style="background-image: url('<?php echo $image[0]; ?>')"></div> |
Find out more about this in the WordPress Codex here.
Recent Comments