News

Add custom backgrounds to WordPress posts

Add a little extra flair to your WordPress posts and pages by employing some unique background images

WordPress

DOWNLOAD TUTORIAL FILEScustomposts

DOWNLOAD TUTORIAL FILES

Create a child theme

Since we’ll be working with the Twenty Twelve theme (http://wordpress.org/extend/themes/twentytwelve) we’ll start by creating a child theme so that we won’t ruin the original theme. Create a folder called twentyten-customback with the following
style.css file in it, upload to wp-content/themes/ and then activate like any other theme in wp-admin.

001 /*
 002 Theme Name: Custom Background Example
 003 Theme URI: http://tdh.me/wordpress/
 004 Author: Thord Daniel Hedengren
 005 Author URI: http://tdh.me/
 006 Description: A child theme for Twenty     Twelve, to demonstrate how to add custom     backgrounds to posts and pages.
 006 Version: 1.0    
 007 License: GNU General Public License v2 or     later
 008 License URI: http://www.gnu.org/licenses/    gpl-2.0.html
 009 Template: twentytwelve
 010 */
 011 @import url('../twentytwelve/style.css');

Plan the meta box

We’ll use a new meta box (since custom fields are too user-unfriendly) which will be added to posts and pages. To keep things simple (for now), we’ll just have this box contain an text input field, where you paste the URL of your custom background image. The meta box will be displayed on the right-hand side when you’re writing and editing a post in wp-admin.

Add the meta box

Create functions.php in the twentytwelve-customback child theme and add the following code to create the meta box. The code will add all meta boxes (just the one in our case) within the customback_background_meta() function, name and place them accordingly. add_meta_box() contains the data, from the box’s name to what post types it should be available on (just posts in our case), where it should be rendered (on the side), and how important it is (core is very important). The box is empty for now, though.

001 <?php
 002 /* META BOXES */
 003 // Create meta boxes
 004 add_action( 'add_meta_boxes', 'customback_    background_meta' );
 005 function customback_background_meta()
 006 {
 007    add_meta_box( 'customback_background_    meta_name', __( 'Custom Background Image',     'customback' ), 'customback_background_meta_    box', 'post', 'side', 'core' );
 010 }
 011 ?>

The meta box function

The actual meta box sits in the customback_background_meta_box() function. This is where we will write the markup for our input field and whatnot, but let’s start by creating the function and have it contain some text in a paragraph tag.

001 // The meta box
 002 function customback_background_meta_box(     $post     )
 003 {
 004    ?>
 005    <p>
 006        Hello, this is the box!
 007    </p>
 008    <?php
 009 }

Fetch stored post meta

When something is written (or selected in some fashion) in a field within a meta box, it is stored in the database. We want to show that when editing posts obviously, so we need to query for the post meta using get_post_meta() and the proper callback. Let’s store that in $url, for the background image URL, for now. This isn’t actual storage of data, rather more like fetching already-stored data.

001 // The meta box
 002 function customback_background_meta_box(     $post     )
 003 {
 004    // Get values for filling in the inputs if     we have them.
 005    $url = get_post_meta( $post->ID, '_    006 customback_background_meta_box_url', true     );
 007    ?>
 008    <p>
 009        Hello, this is the box!
 010    </p>
 011    <?php
 012 }

Nonce away

To add some additional security, we’ll use wp_nonce_field(). This adds some additional validation that tries to make sure that the content submitted by the form is actually from the correct site. We will also add this as well.
 
 001 // The meta box
 002 function customback_background_meta_box(     $post     )
 003 {
 004    // Get values for filling in the inputs if     we have them.
 005    $url = get_post_meta( $post->ID, '_    customback_background_meta_box_url', true );
 006    // Nonce to verify intention later
 007    wp_nonce_field( 'save_customback_        background_meta_box', 'customback_background_    meta_box_nonce' );
 008    ?>
 009    <p>
 010        Hello, this is the box!
 011    </p>
 012    <?php
 013 }

Complete the meta box function

The only thing left is the actual markup for the meta box. This is a simple input field, which will get an appropriate name for later usage, as well as $url as value, so that it will contain whatever is previously stored should there be anything.

001 // The meta box
 002 function customback_background_meta_box(     $post     )
 003 {
 004    // Get values for filling in the inputs if     we have them.
 005    $url = get_post_meta( $post->ID, '_    customback_background_meta_box_url', true );
 006    // Nonce to verify intention later
 007    wp_nonce_field( 'save_customback_        background_meta_box', 'customback_background_    meta_box_nonce' );
 008    ?>
 009    <p>
 010        <label for="background-url">Background     Image URL:</label>
 011        <input type="text" 
 012 id="background-url" name="_customback_    013 background_meta_box_url" value="<?php echo 014 $url; ?>" />
 015    </p>
 016    <p>
 017        <?php _e( "If no URL are given then the     default background image will be used. Don't     forget the <code>http://</code>!", "customback" ); ?>
 018    </p>
 019    <?php`    
 020 }

Save the content

Next up is saving the content when the post is saved, including autosaves. Add the function customback_background_meta_save() to the save_post action, push the nonce to it, and only save if the user in admin has the proper privileges (to edit posts in our case). Finally, save _customback_background_meta_box_url, which incidentally is the name of the input field, remember? The content is escaped so that no nasty HTML or special characters will sneak in there.

001 // Save stuff
 002 add_action( 'save_post', 'customback_    003    background_meta_save' );
 004 function customback_background_meta_save(     $id )
 005 {
 006    if( defined( 'DOING_AUTOSAVE' ) && DOING_    AUTOSAVE ) return;
 007    if( !isset( $_POST['customback_background_    meta_box_nonce'] ) || !wp_verify_nonce( $_    POST['customback_background_meta_box_nonce'],     'save_customback_background_meta_box' ) )     return;
 008    if( !current_user_can( 'edit_post' ) )     return;    
 009    if( isset( $_POST['_customback_background_    meta_box_url'] ) )
 010        update_post_meta( $id, '_customback_    background_meta_box_url', esc_attr( strip_tags( $_POST['_customback_background_meta_box_url'] ) 011 ) );
 012 }

The completed meta box

Now we have a working meta box, which will save its content when the post is saved. Let’s take a look at the completed meta box code before we move on.

 001 // Create meta boxes
 002 add_action( 'add_meta_boxes', 'customback_    background_meta' );
 003 function customback_background_meta()
 004 {
 005    add_meta_box( 'customback_background_    meta_name', __( 'Custom Background Image',     'customback' ), 'customback_background_meta_    box', 'post', 'side', 'core' );
 006 }
 007 // The meta box
 008 function customback_background_meta_box(     $post     )
 009 {    010 // Get values for filling in the inputs if we have them.        
 011    $url = get_post_meta( $post->ID, '_    customback_background_meta_box_url', true );
 012    // Nonce to verify intention later
 013    wp_nonce_field( 'save_customback_        background_meta_box', 'customback_background_    meta_box_nonce' );
 014    ?>
 015    <p>
 016        <label for="background-url">Background     Image URL:</label>
 017        <input type="text" 
 id="background-url" name="_customback_        background_meta_box_url" value="<?php echo     $url; ?>" />    
 018    </p>
 019    <p>
 020        <?php _e( "If no URL are given then the     default background image will be used. Don't     forget the <code>http://</code>!", "customback"     ); ?>
 021    </p>
 022    <?php
 023 }
 024 // Save stuff
 025 add_action( 'save_post', 'customback_        background_meta_save' );        
 026 function customback_background_meta_save(     $id )
 027 {
 028    if( defined( 'DOING_AUTOSAVE' ) && DOING_    AUTOSAVE ) return;
 029    if( !isset( $_POST['customback_background_    meta_box_nonce'] ) || !wp_verify_nonce( $_    POST['customback_background_meta_box_nonce'],     'save_customback_background_meta_box' ) )     030 return;
 031    if( !current_user_can( 'edit_post' ) )     032 return;
 033    if( isset( $_POST['_customback_background_    meta_box_url'] ) )
 034        update_post_meta( $id, '_customback_    background_meta_box_url', esc_attr( strip_tags(     $_POST['_customback_background_meta_box_url'] )     035 ) );
 036 }

A new header.php

The background image, when saved via the meta box, won’t just show up by itself. For this example, we’ll add some code to header.php, so copy that from Twenty Twelve to the twentytwelve-customback and find the body tag (around line 34). After body_class() we’ll add a do_action() with the action hook customback_output.

001 <body <?php body_class(); ?><?php do_    action( 'customback_output' ); ?>>

Create the customback_output hook

Next we’ll create the customback_output hook that do_action() calls. Open functions.php and add the code from the disc, which will add the function customback_output_style, to the action hook customback_output.

Create the customback_output_style function

Naturally we need a function called customback_output_style. This function will output the background image as inline style. We want to make sure this only happens on single posts so the conditional tag is_singular() takes care of that. Since this happens outside of the loop, but we want to get to post meta data, we need the global $post, and finally we’ll just echo the inline style and fetch the contents from _customback_background_meta_box_url with get_post_meta().

001 function customback_output_style() {
 002     // Just on singulars
 003    if ( is_singular() ) {
 004        global $post;
 005        echo 'style="background-image: url('';
 006        echo get_post_meta( $post->ID, '_    customback_background_meta_box_url', true );
 007        echo '');"';
 008    }
 009 }

Add a background Image

Let’s give it a go, shall we? Write a post and add an URL to the background image URL input field. Then it’s time to publish!

In all its glory

And there we are, the post has its very own background image that will only be used there to illustrate it. Hopefully you’ll pick a slightly more better looking one, because this one wasn’t too suitable for this particular purpose…

Why stop there?

While it would be nice to add checkboxes for various background properties, we’ll keep it simple and raw. The idea is to add an input field where the tech-savvy person can add additional inline style.

The CSS input field

We need to update the customback_background_meta_box() function in functions.php with two things. First there’s the new $style which will make sure that the saved content will be shown in the meta box, much like $url. Then there’s the markup for the new input box.

Save everything

We need to update the function for saving the content as well, customback_background_meta_save that is. We’ll use update_port_meta() with _customback_background_meta_box_style, much like we did with _customback_background_meta_box_url.

001 // Save stuff
 002 add_action( 'save_post', 'customback_        background_meta_save' );
 003 function customback_background_meta    _save(     $id )
 004 {
 005    if( defined( 'DOING_AUTOSAVE' ) &&     DOING_    AUTOSAVE ) return;
 006    if( !isset( $_POST['customback_        background_    meta_box_nonce'] ) || !wp_verify_    nonce( $_    POST['customback_background_meta_    box_nonce'],     'save_customback_background_    meta_box' ) )                              007 return;
 008    if( !current_user_can( 'edit_post' ) )     009 return;
 010    if( isset( $_POST['_customback_        background_    meta_box_url'] ) )
 011        update_post_meta( $id, '_customback_    background_meta_box_url', esc_attr( strip_    tags(     $_POST['_customback_background_meta_    box_url'] )     ) );    
 012    if( isset( $_POST['_customback_        background_    meta_box_style'] ) )
 013        update_post_meta( $id, '_customback_    background_meta_box_style', esc_attr( strip_    tags( $_POST['_customback_background_meta_    box_    style'] ) ) );
 014 }

Output the new inline style

We don’t need to do any changes to header.php, but we do need to alter the function with the content we’re hooking onto our do_action() there. This is basically just another echo where we output the contents of _customback_background_meta_box_style. Some minor edits for the closing echo are needed too, since you want the url() parenthesises to just simply wrap the background image URL.

001 // Function to output the styling
 add_action( 'customback_output',         'customback_    output_style' );
 002 function customback_output_style() {
 003    // Just on singulars
 004    if ( is_singular() ) {
 005        global $post;
 006        echo 'style="background-image:         url('';            echo get_post_meta( $post->ID,     '_customback_background_meta_box_url', true     );
 007        echo ''); ';
 008        echo get_post_meta( $post->ID, '_    customback_background_meta_box_style', true     );
 009        echo '"';
 010    }
 011 }

Let’s try it out

Let’s try this new field, shall we? For this example, I use a photo that I want to scale to 100%, and keep fixed.

In all its glory, redux

There we are, a photo scaled to 100%, without repeating the background, and with the background image fixed.

×