Use WordPress Post Thumbnail as Background image


Now and then you need in a post or page a catchy image. For editors the thumbnail function is quite comfortable to assign an image to a post or a page. Therefore it is worthwhile to use this picture as a background image for the post. However, it is much better if the image is defined via CSS in the background and it doesn’t appear in the markup. Therefore, a small function that defines a default image and if there is a defined post thumbnail, then this will be used.

The function is only a small solution, therefore, it must be adapted and expanded to your liking. Have fun.

/**
 * return post thumbnail inside style in head
 */
if ( !function_exists('fb_background_image') ) {
	
	function fb_background_image() {
		// only frontend
		if ( is_feed() || is_trackback() ) {
			return;
		}
		
		// default image, when no set an post thumbnail
		if ( !has_post_thumbnail($GLOBALS['post']->ID) ) {
			$style = '' . "\n\n";
		} else {
			// get post thumbnail
			$image = wp_get_attachment_image_src(
				get_post_thumbnail_id($GLOBALS['post']->ID),
				'banner' // size for image; defined via add_image_siz
			);
			
			$style = sprintf(
				'',
				esc_attr($image[0]),
				"\n\n"
			);
		}
		if ($style)
			echo $style;
	}
	
	// add functions
	add_action( 'wp_head', 'fb_background_image' );
	add_theme_support( 'post-thumbnails' );
	add_image_size( 'banner', 980, 350, true );
	
}

Posted

in

by

Comments

One response to “Use WordPress Post Thumbnail as Background image”

  1. danix Avatar

    the whole world of customization behind wordpress is really fascinating…

    I must say thank you for every snippet you share with us, it’s a great way to learn all the “magic” behind this great CMS…

    really thanks alot!!!