是否可以将背景图像附加到div而不是正文?

时间:2013-09-07 作者:Rubens Mariuzzo

目前,通过WordPress添加自定义背景图像会将其附加到<body>. 是否有一个钩子告诉WordPress将背景图像附加到另一个元素?

而不是让WordPress生成:

body.custom-background {
    background-color: #ffffff;
    background-image: url(\'background.jpg\');
    background-repeat: no-repeat;
    background-position: top center;
    background-attachment: scroll;
}
我想自定义WordPress,使我能够将自定义背景附加到另一个元素而不是正文。

1 个回复
最合适的回答,由SO网友:Charles Clarkson 整理而成

默认情况下,WordPress使用_custom_background_cb() 函数创建问题中显示的样式。您可以将自己的函数添加到add_theme_support() 在您的主题中。

add_theme_support( \'custom-background\', array( \'wp-head-callback\' => \'wpse_113346_custom_background_cb\' ) );
最初,您可以使用_custom_background_cb() 功能为您自己的功能:

/**
 * 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
}
此时,您应该测试它以确保它正常工作。测试完成后,您可以开始更改wpse_113346_custom_background_cb() 根据您的喜好自定义输出。

结束

相关推荐