X

How To Alter the Default Background Behaviour

Snippets by IsItWP

Do you want to alter the default background behavior? This snippet will let you customize any background parameter you want, as well as the element on which it’s applied.

Instructions

All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:

// Activate custom background and set callback function
if ( function_exists( 'add_theme_support' ) ) {
    $defaults = array(
        'default-color' => '000000',
        'default-image' => get_template_directory_uri() . '/img/background.png',
        'wp-head-callback' => 'my_theme_background_cb',
        'admin-head-callback'    => '',
        'admin-preview-callback' => ''
    );
    add_theme_support( 'custom-background', $defaults );
}
// Callback function to alter custom background behavior
function my_theme_background_cb() {
    $background = get_background_image();
    $color = get_background_color();
 
    if ( ! $background && ! $color )
        return;
 
    $style = $color ? "background-color: #$color;" : '';
 
    if ( $background ) {
        $image = " background-image: url('$background');";
 
        $repeat = get_theme_mod( 'background_repeat', 'repeat' );
        if ( ! in_array( $repeat, array( 'no-repeat', 'repeat-x', 'repeat-y', 'repeat' ) ) )
                $repeat = 'repeat';
        $repeat = " background-repeat: $repeat;";
 
        $position = get_theme_mod( 'background_position_x', 'left' );
        if ( ! in_array( $position, array( 'center', 'right', 'left' ) ) )
                $position = 'left';
        $position = " background-position: top $position;";
 
        $attachment = get_theme_mod( 'background_attachment', 'scroll' );
        if ( ! in_array( $attachment, array( 'fixed', 'scroll' ) ) )
                $attachment = 'scroll';
        $attachment = " background-attachment: $attachment;";
 
        $style .= $image . $repeat . $position . $attachment;
    }
?>
    <!-- You can set any class or id target here -->
    <style type="text/css" id="custom-background-css">;
        .main { <?php echo trim( $style ); ?> }
    </style>
<?php } 

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out WPBakery Page Builder Review.

Comments   Leave a Reply

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!