How to add featured images before entry on single Posts in Genesis

Posted on
5/5 - (122 votes)

In Genesis Slack a user asked,

Hello everyone, I’m working on a custom theme and I’d like to customize my featured image to look like this: https://preview.arraythemes.com/publisher/2015/05/20/heydays-branding/

We can register a custom image size for the featured images on single Posts and display the featured image (if present) using genesis_before_entry hook in Genesis.

Step 1

Add the following in child theme’s functions.php:

// Register a custom image size for featured image on single Posts.
add_image_size( 'post-image', 900, 540, true );

add_action( 'genesis_before_entry', 'sk_featured_image' );
/**
 * Display featured image (if present) before entry on single Posts
 */
function sk_featured_image() {
    // if we are not on a single Post having a featured image, abort.
    if ( ! ( is_singular( 'post' ) && has_post_thumbnail() ) ) {
        return;
    }

    // get the URL of featured image.
    $image = genesis_get_image( 'format=url&size=post-image' );

    // get the alt text of featured image.
    $thumb_id = get_post_thumbnail_id( get_the_ID() );
    $alt = get_post_meta( $thumb_id, '_wp_attachment_image_alt', true );

    // if no alt text is present for featured image, set it to Post title.
    if ( '' === $alt ) {
        $alt = the_title_attribute( 'echo=0' );
    }

    // get the caption of featured image.
    $caption = get_post( $thumb_id )->post_excerpt;

    // build the caption HTML if caption is present for the featured image..
    $caption_html = $caption ? '<figcaption class="wp-caption-text">'. $caption . '</figcaption>' : '';

    // display the featured image with caption (if present) beneath the image.
    printf( '<figure class="single-post-image wp-caption"><img src="%s" alt="%s" />%s</figure>', esc_url( $image ), $alt, $caption_html );
}

Thanks to Gary Jones for helping in the past with the code for setting alt text to that of the image, if present otherwise to entry title.

Step 2

Regenerate thumbnails.

Step 3

Add the following in child theme’s style.css:

.single-post-image img {
    vertical-align: top;
}