Skip to content

Instantly share code, notes, and snippets.

@pommiegranit
Created November 12, 2014 00:57
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save pommiegranit/0fa601890a7c31113ada to your computer and use it in GitHub Desktop.
Make featured image background on WP posts and most recent post's featured image background on home page.
// Custom Background Images
// Use featured image on posts
// Use the most recent post's featured image on home page (or default background image)
function add_background_image() {
global $post;
if (is_admin()) return;
// get the global background image
$page_bgimg_url = get_background_image();
// if home then override default with most recent post
if ( is_front_page() || is_home() ) {
$posts = get_posts( array('posts_per_page'=>1,'orderby'=>'post_date','order'=>'desc') );
echo $posts[0]->ID;
if ($posts) {
$page_bgimg = wp_get_attachment_image_src( get_post_thumbnail_id( $posts[0]->ID ), 'full' );
$page_bgimg_url = $page_bgimg[0]; // this returns just the URL of the image
}
}
// if single and single active
if ( is_single() ) {
// check to see if the theme supports Featured Images, and one is set
if (has_post_thumbnail( $post->ID )) {
// specify desired image size in place of 'full'
$page_bgimg = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' );
$page_bgimg_url = $page_bgimg[0]; // this returns just the URL of the image
}
}
// get background image for a category
if ( is_archive() && function_exists('category_image_src') ) {
if ( category_image_src() != '' ) {
$page_bgimg_url = category_image_src();
}
}
// write out css
if ($page_bgimg_url != '') {
echo '
<style type="text/css" id="custom-background-css-override">
body {
background: url(' . $page_bgimg_url . ') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
</style>';
}
}
add_action('wp_head' , 'add_background_image' , 9999);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment