Created
November 12, 2014 00:57
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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