2

Currently, adding a custom background image via WordPress will attach it to the <body>. Is there a hook to tell WordPress to attach the background image to another element?

Instead of having WordPress generating:

body.custom-background {
    background-color: #ffffff;
    background-image: url('background.jpg');
    background-repeat: no-repeat;
    background-position: top center;
    background-attachment: scroll;
}

I would like to customize WordPress in a way that allow me to attach that custom background to another element instead of body.

2

By default, WordPress uses the _custom_background_cb() function to create the style you show in your question. You can use a function of your own by adding it to the add_theme_support() in your theme.

add_theme_support( 'custom-background', array( 'wp-head-callback' => 'wpse_113346_custom_background_cb' ) );

Initially, you can use the guts of the _custom_background_cb() function for your own function:

/**
 * My custom background callback.
 */
function wpse_113346_custom_background_cb() {
    // $background is the saved custom image, or the default image.
    $background = set_url_scheme( get_background_image() );

    // $color is the saved custom color.
    // A default has to be specified in style.css. It will not be printed here.
    $color = get_theme_mod( '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;
    }
?>
<style type="text/css" id="custom-background-css">
body.custom-background { <?php echo trim( $style ); ?> }
</style>
<?php
}

At this point, you should test it to make sure it works okay. Once tested, you can start making changes to wpse_113346_custom_background_cb() to customize the output to your liking.

  • Thanks! After doing some research I found this is the only way to do it. – Rubens Mariuzzo Sep 9 '13 at 14:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.