How to change featured image location conditionally in Genesis based on Page’s layout

Posted on

In Facebook’s Genesis group, a user asked:

I have some three column (sidebar/content/sidebar-alt) and some two column (sidebar/content) pages. In the three column pages I’m putting the featured image at the top of the content-sidebar wrap, which places it over the content area and the secondary sidebar. In the two column pages, I want the featured image to be at the top of the content area. I’m trying to set up a conditional statement in the functions.php to distinguish between the two situations.

This can be done by getting the layout the current Page uses, checking it against sidebar-content-sidebar and content-sidebar layouts and hooking genesis_image() to the correct action hook according to the desired location for the featured image.

Step 1

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

// Register custom image size for featured image on static Pages
add_image_size( 'static-page', 1200, 250, true );

// Call the function to display featured image depending on which layout is in use on static Pages
add_action( 'genesis_after_header', 'sk_conditional_featured_image' );
function sk_conditional_featured_image() {

	// if we are not on a static Page, abort.
	if ( ! is_singular( 'page' ) ) {
		return;
	}

	// get the page layout
	$site_layout = genesis_site_layout();

	// if the page uses sidebar-content-sidebar layout, show featured image above sidebar-content-sidebar.
	if ( 'sidebar-content-sidebar' == $site_layout ) {
		add_action( 'genesis_before_content_sidebar_wrap', 'sk_featured_image' );
	}

	// if the page uses content-sidebar layout, show featured image above content.
	if ( 'content-sidebar' == $site_layout ) {
		add_action( 'genesis_before_entry', 'sk_featured_image' );
	}

}

// Function to display featured image
function sk_featured_image() {

	genesis_image( array( 'size' => 'static-page' ) );

}

Step 2

Regenerate thumbnails.

Step 3

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

.attachment-static-page {
	margin-bottom: 40px;
	vertical-align: top;
}