Skip to content

Instantly share code, notes, and snippets.

@daronspence
Created July 27, 2015 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daronspence/30881fb5cf3b7838339b to your computer and use it in GitHub Desktop.
Save daronspence/30881fb5cf3b7838339b to your computer and use it in GitHub Desktop.
Add a background image via a custom field and no theme hacking.
<?php
add_filter( 'the_content', function( $content ){
// Just pretend you have a custom metabox that saves the ID for you.
$image_id = get_post_meta( 'custom_image', $post->ID );
$image_src = ''; // instantiate variable
if ( !empty( $image_id ) ){
$image_src = wp_get_attachment_image_src( $image_id, 'large');
}
if ( !empty( $image_src ) ){
return "<div class='has-bg-image' style='background-image: url(\" {$image_src} \" );'>" . $content . "</div>";
}
// fallback for if there is no image
return $content;
}, 10, 1 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment