Adding Custom Fields for Img in Posts

You should use the post thumbnail feature. Add support for this feature with this line in your functions.php file:

add_theme_support( 'post-thumbnails' );

You can also set a new thumbnail size that will be cropped on new added photos to use this in your theme. Add this code to set a new thumbnail size (also in the functions.php file):

add_image_size( 'large-feature', 500, 300, true );

The code above crops the picture to fit exact into 500×300 pixel. to let the width and heigh to be fluid (with a max width of 500 and a max height of 300) set the true property to false.

Finally add the thumbnail to the theme at the location you want. With this code:

echo get_the_post_thumbnail( $post->ID, 'large-feature' );

That’s it 🙂 you enabled and customized a post thumbnail pictured! Hope this works for you 🙂

Edit

Adding a couple suggestions/best practices:

First, be sure to put the functions.php code inside a callback, hooked in appropriately; e.g.:

function theme_slug_setup_thumbnails() {
    // Enable featured image feature
    add_theme_support( 'post-thumbnails' );
    // Add custom image size for displaying
    // featured image within the post
    add_image_size( 'large-feature', 500, 300, true );

}
add_action( 'after_setup_theme', 'theme_slug_setup_thumbnails' );

Second, wrap the template call in a conditional, and output the fully-formed HTML for the image:

if ( has_post_thumbnail() ) {
    the_post_thumbnail( 'large-feature' );
}

(I would also recommend using a unique slug for the custom image size, such as theme-slug-large-feature', wheretheme-slugis the *slug* of your Theme name. Note that I also usedtheme_slugas a unique prefix for thefunctions.php` callback function.)

Leave a Comment