Skip to content

Instantly share code, notes, and snippets.

@scofennell
Last active August 29, 2015 14:01
Show Gist options
  • Save scofennell/f11b65cb3b267e33548f to your computer and use it in GitHub Desktop.
Save scofennell/f11b65cb3b267e33548f to your computer and use it in GitHub Desktop.
WordPress function to return a block of CSS for displaying and positioning a full-page background image.
<?php
/**
* Returns a block of CSS for displaying and positioning a full-page background image
*
* @return string|bool A block of CSS for displaying and positioning a full-page background image or false on failure
*/
function sjf_deh_the_bg_image_styles(){
// this function won't work if $post is not set (which would be the case on a 404 page, for example)
$post = get_post();
if( empty( $post ) ) { return false; }
// we'll use this to get post meta for curating the position for this image
$post_id = absint( $post->ID );
// the src for the image, accounting for mobile devices likely being best-served with a smaller version
$src = esc_url( sjf_deh_get_image_src() );
if( empty( $src ) ) { return false; }
// grab and sanitize the value for where to vertically position the image, defaults to 'center'
$vertical_position = 'center';
if( get_post_meta( $post_id, 'sjf_deh_vertical_position', TRUE ) ) { $vertical_position = get_post_meta( $post_id, 'sjf_deh_vertical_position', TRUE ); }
$vertical_position = sjf_deh_alphanum( $vertical_position );
// grab and sanitize the value for where to horizontally position the image, defaults to 'center'
$horizontal_position = 'center';
if( get_post_meta( $post_id, 'sjf_deh_horizontal_position', TRUE ) ) { $horizontal_position = get_post_meta( $post_id, 'sjf_deh_horizontal_position', TRUE ); }
$horizontal_position = sjf_deh_alphanum( $horizontal_position );
// grab and sanitize the value for how to size the image, defaults to 'cover'
$background_size = 'cover';
if( get_post_meta( $post_id, 'sjf_deh_background_size', TRUE ) ) { $background_size = get_post_meta( $post_id, 'sjf_deh_background_size', TRUE ); }
$background_size = sjf_deh_alphanum( $background_size );
// echo the css for displaying our background image
echo"
<!-- styles added by sjf_deh_the_bg_image_styles() to position the page bg image -->
<style>
#page {
background: url($src) no-repeat $horizontal_position $vertical_position fixed;
-webkit-background-size: $background_size;
-moz-background-size: $background_size;
-o-background-size: $background_size;
background-size: $background_size;
}
</style>
";
}
add_action( 'wp_head', 'sjf_deh_the_bg_image_styles' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment