Auto Resize Background Images With BackStretch

Many of the Pro WordPress designers are using jQuery script named Backstretch.

The code will automatically re-size your background images to fit the size of the window.

Once you add the code to your js folder, all you need to do is paste the PHP functions code into you child themes functions.php file.

Let’s take a look at how best to install the jQuery and PHP code.

There’s 2 steps you need to follow:

  1. Create 2 new .js files placed inside a new folder named js in your child themes root directory
  2. Add PHP code to your child themes functions.php file.

BackStretch Scripts

You will need to create 2 new files using a code editor like Notepad++.

The names of the files as exactly the same as the names in this Gist:

backstretch.js and backstretch-set.js

Here’s what the folder looks like in your child themes root directory:

file structure

And here’s what the 2 .js files look like inside the js folder.

javascript folder

Here’s the code which goes in these 2 files:

PHP Functions

You’ll also need to take the PHP code from the above Gist and paste it into your child themes functions.php file.

That’s it.

You can now go to Appearance > Background and upload your background image.

upload background image

Only Display Background Image On Specific Pages

You can also add a conditional tag to the PHP code of you only want the background image to display on specific pages.

This code is a visual guide on where to add the conditional tag.

//* Enqueue Backstretch script and prepare images for loading
add_action( 'wp_enqueue_scripts', 'agency_enqueue_backstretch_scripts' );
function agency_enqueue_backstretch_scripts() {

<pre><code>//* Load scripts only if custom background is being used
if ( ! get_background_image() )
    return;
if ( is_home() )
wp_enqueue_script( 'agency-pro-backstretch', get_bloginfo( 'stylesheet_directory' ) . '/js/backstretch.js', array( 'jquery' ), '1.0.0' );
wp_enqueue_script( 'agency-pro-backstretch-set', get_bloginfo( 'stylesheet_directory' ).'/js/backstretch-set.js' , array( 'jquery', 'agency-pro-backstretch' ), '1.0.0' );

wp_localize_script( 'agency-pro-backstretch-set', 'BackStretchImg', array( 'src' =&gt; get_background_image() ) );
</code></pre>

}

You can see the conditional tag: is_home() has been added immediately before the wp_enqueue_script. Change the conditional tag to suit your own preferences.

Theme Background Support

Once you’ve added the .js script, go to Appearance -> Background and upload a large background image.

If your theme already includes support for a custom background, open up your child themes functions.php file and remove the line of code that looks like this:

add_theme_support( 'custom-background' );

The code for supporting custom background images is already included in the Github Gist above so no need to include it twice.

You can also use this script to resize images for your header, footer and different block level elements.

Other Ways To Use Backstretch

You can also paste this code directly into your template files to display the background image

[/code]

Backstretch Slideshow

Add the path to your images to create a background slide show. [code] [/code] If backstretch isn't for you, here's a few simple tips on how to style the background of your theme.

Related Tutorials


Comments

46 responses to “Auto Resize Background Images With BackStretch”

  1. Debbie Hastings Avatar
    Debbie Hastings

    Having trouble with the manual input – it’s not responsive. It just cuts the size off the edges as the screen gets smaller. Am I missing something?

    1. Might not be the best solution. Which element did you want to add the background to and using which theme?

  2. I’ve installed the manual version which works well. There is a fade built into this solution:
    [code]
    jQuery(document).ready(function($) {
    $(“body”).backstretch([BackStretchImg.src],{duration:3000,fade:750});
    });
    [/code]
    How would I change this to make the image fade in faster, or eliminate the fade-in all together?

    Thanks.

    1. Brad Dalton Avatar
      Brad Dalton

      Try changing the values for fade :750 and duration:3000

  3. fotod0g13 Avatar
    fotod0g13

    Hi Brad,
    I manually added the Bootstretch code to the Genesis> Metric theme.
    I go the background image to load but it does not seem to be responsive in any way
    ( the background image)

    here is the site: http://harelydavidsonservicenyc.com

    wondering If I am missing something here?
    thoughts?
    thanks

    Scott

    1. Brad Dalton Avatar
      Brad Dalton

      Let me have a go. I don’t think it will work on the old XHTML themes.

    2. Brad Dalton Avatar
      Brad Dalton

      Line 47 of style.css, this is the problem

      [code]
      /***** Wrap ********************/

      .metric .site-container {
      background: url(images/wrap.png) top center no-repeat;
      margin: 0 auto 0;
      padding: 0;
      }

      .site-container {
      background: #F7F7F7 url(images/wrap-bg.png) repeat-x;
      margin: 0 auto;
      min-width: 960px;
      padding: 0;
      }
      [/code]

    3. Brad Dalton Avatar
      Brad Dalton

      Did you want it to load on the home page only or the entire site?

  4. I’ve completed these steps and it looks great on my laptop, but on my large monitor the image is displaying from the top down rather than centering it vertically. Here you can see what I mean: http://s29.photobucket.com/user/suburbanite/media/buildings_zpsfba95119.jpg.html

    When shown on a laptop, the image seems centered vertically within the image pane, but on a larger screen, it seems to be displaying it vertically aligned to the top of the image if that makes sense. My site is located here: http://cornerstone.angelawdesign.com/

    Thanks Brad!

  5. uwitness Avatar
    uwitness

    I came across this post as I’ve been trying to add Backstretch to a Genesis site I’m building. In my case I’m using a plugin – Easy Backstretch – but the Backstretch script itself isn’t any different from the standalone one. But I’m having a problem with the background in IE11 on Windows 8/8.1 only, in that when scrolling the background is excessively jerky (a known IE11/Win8 bug with fixed backgrounds, apparently). I’ve tried adding the Backstretch script via this method and still getting that in IE11. I noticed that the Agency Pro child theme is fine in IE11 – no jerking, jumping at all – but the 411 Pro has the exact same issue. Do you have any idea what’s different in Agency Pro that remedied the problem?

    1. Brad Dalton Avatar
      Brad Dalton

      I would say the code is different.

      The Javascript maybe the same but the PHP and CSS would be different.

      I think if you compare the CSS in the plugin to what the Agency Pro theme uses, you will see the difference.

  6. Gary Hart Avatar
    Gary Hart

    Brad, thanks for sharing your knowledge. I added your code with partial results to Centric Pro. The background image reduces to a limit: http://www.sftpa.org. Did I miss something? Thank you in advance. Gary

    1. Brad Dalton Avatar
      Brad Dalton

      Hi Gary

      Looks ok. Did you want a different result?

      I think with that image its a good result.

      1. Gary Hart Avatar
        Gary Hart

        Brad, it’s stops scaling in an iPhone vertical mode; sides cut off, but scales properly in horizontal mode. Thanks, Gary

        1. Brad Dalton Avatar
          Brad Dalton

          Because of the image or the code in the theme?

          1. Gary Hart Avatar
            Gary Hart

            I’m not sure Brad, I created the files and used your code as per your instructions. The image is 1280 wide. Is there an optimum size?

            As soon as we settle on a design plan, I’d like to see if you can make a few mods for us. We’re testing functionality right now.

            Thanks,
            Gary

          2. Brad Dalton Avatar
            Brad Dalton

            There’s no optimal size because it depends on whats in the image and other factors so you just need to test what works best.

  7. Ryan Dolan Avatar
    Ryan Dolan

    How would I set backstretch to display on a div other than body?
    For example I am using Epik theme with homepage and I want the css class of one of the home widget areas to have a background image with backstretch

    1. Brad Dalton Avatar
      Brad Dalton

      Hello Ryan

      I would ask the Epic support forum for this as they have the most experience with that theme.

      Another option is to use a plugin which enables you to use Backstretch with any class.

  8. Tania Avatar

    Yes. Got it to work.
    What aspect ratio should I look at for the best effect using backstretch? Does it matter?

    1. Brad Dalton Avatar
      Brad Dalton

      Tania

      If someone copies and pastes your code it will break their site because you haven’t embedded it properly. Did you see this? Pasting Code: Please use Github Gists & paste the embed code link here.

      1. Tania Avatar

        Sorry.
        Missed that! See it now of course.
        T

  9. Is it possible to use if ( ! genesis_get_image() ) to use the featured image as the background image on the inner pages?

    1. Brad Dalton Avatar
      Brad Dalton

      Hello Tania

      Did you test this?

      What have you tried so far?

  10. Hi there Brad. I have been working on the following as a plugin to get full background image based on a custom metabox
    [code]
    /**
    * Adds a box to the main column on the Page edit screens.
    */
    function myplugin_add_custom_box() {
    $screens = array(‘page’);
    foreach ( $screens as $screen ) {
    add_meta_box(
    ‘myplugin_sectionid’,
    __( ‘My Full Bcakground Image’, ‘myplugin_textdomain’ ),
    ‘myplugin_inner_custom_box’,
    $screen
    );
    }
    }
    add_action( ‘add_meta_boxes’, ‘myplugin_add_custom_box’ );

    /**
    * Prints the box content.
    * @param WP_Post $post The object for the current post/page.
    */
    function myplugin_inner_custom_box( $post ) {
    // Add an nonce field so we can check for it later.
    wp_nonce_field( ‘myplugin_inner_custom_box’, ‘myplugin_inner_custom_box_nonce’ );

    /*
    * Use get_post_meta() to retrieve an existing value
    * from the database and use the value for the form.
    */
    $bg = get_post_meta( $post->ID, ‘_my_meta_value_key’, true );
    echo ”;
    _e( “Image path: /images”, ‘myplugin_textdomain’ );
    echo ‘ ‘;
    echo ”;
    }

    /*
    * When the post is saved, saves our custom data.
    *
    * @param int $post_id The ID of the post being saved.
    */
    function myplugin_save_postdata( $post_id ) {
    /*
    * We need to verify this came from the our screen and with proper authorization,
    * because save_post can be triggered at other times.
    */
    // Check if our nonce is set.
    if ( ! isset( $_POST[‘myplugin_inner_custom_box_nonce’] ) )
    return $post_id;
    $nonce = $_POST[‘myplugin_inner_custom_box_nonce’];
    // Verify that the nonce is valid.
    if ( ! wp_verify_nonce( $nonce, ‘myplugin_inner_custom_box’ ) )
    return $post_id;
    // If this is an autosave, our form has not been submitted, so we don’t want to do anything.
    if ( defined( ‘DOING_AUTOSAVE’ ) && DOING_AUTOSAVE )
    return $post_id;
    // Check the user’s permissions.
    if ( ‘page’ == $_POST[‘post_type’] ) {

    if ( ! current_user_can( ‘edit_page’, $post_id ) )
    return $post_id;
    }
    /* OK, its safe for us to save the data now. */
    // Sanitize user input.
    $mydata = sanitize_text_field( $_POST[‘myplugin_new_field’] );
    // Update the meta field in the database.
    update_post_meta( $post_id, ‘_my_meta_value_key’, $mydata );
    }
    add_action( ‘save_post’, ‘myplugin_save_postdata’ );//end

    /*
    * Change fullscreen background images per post/page in wordpress
    */
    add_action(‘wp_head’, ‘insert_post_bg’);
    function insert_post_bg() {
    if (!is_page()) return;
    global $post;
    $bg = get_post_meta($post->ID, ‘_my_meta_value_key’, true);
    if (!empty($bg)) {
    echo ‘google.load(“jquery”, “1”);$(“body”).ezBgResize({img : “‘.dirname( get_bloginfo(‘stylesheet_url’) ).’/images/’.get_post_meta($post->ID, ‘_my_meta_value_key’, true).'”});’;
    }
    }
    [/code]

    I only tested it on my imac (chrome) and it works, but I haven’t test it on small devices yet.
    I would love to get a second alternative just in case.
    Is the BackStretch working on all devices? I though I came across something that says otherwise.

    1. Brad Dalton Avatar
      Brad Dalton

      I like the Backstrecth plugin by Andrew Norcross and the support is excellent.

      You would need to test it on all devices to check if it works the way you want.

  11. Great plugin!
    I am just wondering how one can easily have different background on different pages?

    1. Brad Dalton Avatar
      Brad Dalton

      You can do that with code but it depends on how many pages. If its every single page, you’d be better off to use a plugin like Background Manager http://wordpress.org/plugins/background-manager/

  12. Jason DiSenso Avatar
    Jason DiSenso

    Brad,

    Is there a way to use this functionality and offer say 5 random images site-wide on Agency? What is the conditional code for that?

  13. Thomas Townsend Avatar
    Thomas Townsend

    What if I wanted to use a different image on different pages and still have the BG images stretch feature ?

    Thanks

    1. Brad Dalton Avatar
      Brad Dalton

      Already included a link to that solution in this post Thomas.

    2. Thomas Townsend Avatar
      Thomas Townsend

      Brad, appreciate the reply. I had seen the link and actually had it installed as optional before I viewed your post. The information you provided on that link is way more informational than whats on plugin page and or the plugin itself. I was not aware you could affect each individual page from within the page/post settings.

      Is there a way I could do this with the native code in the functions.php vs having to use that and a plug-in as I am now?

      Thanks again for your informative posts.

      1. Brad Dalton Avatar
        Brad Dalton

        Yes, you can add conditional tags to the code after the function to control exactly where it displays.

        Or you can paste it into any template if you only want it to display on pages using that template.

  14. Brad,

    Do you know if it’s possible to control the backstretch image ratio from the php, perhaps using the centeredX option??

    JohnC

    1. Brad Dalton Avatar
      Brad Dalton

      Hi John

      Are you using the Easy Backstretch plugin or the code?

      1. Was trying to do it with code. The older version of minimum has a full width image called home-featured so I’ve been playing with copy/paste of that and am working out the styling now but its not clear if this the best approach or if its outdated. I was trying to do this without using a plugin (both to learn and to minimize plugin overhead). It seemed that backstretch would be an interesting approach but I am not keen on the way it will play with the aspect ratio. At the end of the day I simply want a static image that spans the frame and is responsive.

        jc

  15. Aaron Hartland Avatar
    Aaron Hartland

    Hi Brad – Do you know if there is an easy way to use the Genesis featured image (if present) on each page for the backstretch image and default to the background image if absent?

    1. Brad Dalton Avatar
      Brad Dalton

      Hi Aaron

      Its doable however there’s no plugin i know of to do that.

      Just a matter of using the correct code.

      There is a plugin to add BackStretch however it only offers provision for one background image so you could also use the code from that plugin another option.

  16. ok, sorry i’m to dumb an not that programmer-guy… can you help me?
    i wan’t to integrate it for wordpress 3.6 with them twenty twelve for my setted background.

    i try it with Enqueue Javascripts methode but it didnt works.

    my last try was, just to get that in the functions.php:

    “add_action( ‘wp_enqueue_scripts’, ‘theme_enqueue_scripts’ );
    function theme_enqueue_scripts() {

    if ( ! get_background_image() )
    return;

    wp_enqueue_script( ‘twentytwelve’, get_bloginfo( ‘stylesheet_directory’ ) . ‘/js/jquery.backstretch.min.js’, array( ‘jquery’ ), ‘1.0.0’ );

    }”

    1. Brad Dalton Avatar
      Brad Dalton

      Its a fair bit of work to write that code and test it for non Genesis themes.

  17. Andre Avatar

    Hi Brad,

    No, I didn’t even know they already have 2.0 out? You’re pointing to HTML5 for audio, correct?

    Andre

    1. Brad Dalton Avatar
      Brad Dalton

      HTML 5 support for all StudioPress child themes and HTML built into the Genesis core.

      You can download the new version of Genesis which is in Beta from the downloads page.

      The only child theme which is compatible at the moment is the Genesis 2.0 Sample theme

  18. Andre Avatar

    Hi Brad,

    Yes, that’s what was creating the problem. Many thanks!

    Andre

    1. Brad Dalton Avatar
      Brad Dalton

      Now worries Andre.

      Have you tried Genesis 2.0 yet with HTML 5 support in your child theme?

  19. Andre Avatar

    Hey Brad,

    I’m encountering an issue with the backstretch in the Metro theme. Is there a way to disable the fade and duration?

    http://www.iamsignificant.ca

    jQuery(document).ready(function($) {
    $(“body”).backstretch([BackStretchImg.src],{duration:3000,fade:750});
    });

    When I get the site opened in Firefox first, I see the background, if I then CTRL-F5, then the background doesn’t load. If I CTL-F5 again, nor the slider gallery nor the post thumbnails load.

    Thanks!

    Andre

    1. Brad Dalton Avatar
      Brad Dalton

      Hi Andre

      Can’t you simply remove those parameters from the code?

      Try removing just this part

      ,{duration:3000,fade:750}

Leave a Reply

Join 5000+ Followers

Get The Latest Free & Premium Tutorials Delivered The Second They're Published.