使用定制器设置div的背景图像

时间:2017-03-06 作者:JonHerbert

我正在尝试使用customiser将每个“帖子块”的背景图像设置为我选择上载的任何图像的背景图像。这是到目前为止我的代码。

function jhwdblog_customize_register( $wp_customize ) {
    $wp_customize->add_section( \'post_box_image_section\' , array(
            \'title\'      => __( \'Post Box Background\', \'jhwdblog\' ),
            \'description\' => \'Upload a logo to replace the post box background image\',
            \'priority\'   => 30,
    ));

    $wp_customize->add_setting( \'post_box_image\');

    $wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, \'post_box_image\', array(
            \'label\'      => __( \'Post Box Image\', \'jhwdblog\' ),
            \'section\'    => \'post_box_image_section\',
            \'settings\'   => \'post_box_image\',
    )));
}
add_action( \'customize_register\', \'jhwdblog_customize_register\' );
在我的页面中,我试图将其添加到样式内联中,如下所示

<div class="post-block" style="background-image:url(\'<?php echo esc_url(get_theme_mod( \'post-box-image\' )); ?> \');">
然而,当我检查检查器时,得到的只是背景图像:url((未知))。我错过了什么?

2 个回复
最合适的回答,由SO网友:JonHerbert 整理而成

解决方法:首先,有一个拼写错误,我用的是“post box image”,而不是“post\\u box\\u image”。。。

其次,最好在函数中这样做。php:

function jhwd_blog_theme_customize_css()
{
?>
    <style type="text/css">
        .post-block { 
            background-image:url(\'<?php echo get_theme_mod( \'post_box_image\' );?>\'); 
            background-color: <?php echo get_theme_mod( \'post_box_color\' );?>;
        }
        .post-block>h1, .post-boxes {
            background-color: <?php echo get_theme_mod( \'post_boxes_items_color\' );?>;
        }
    </style>
<?php
}
add_action( \'wp_head\', \'jhwd_blog_theme_customize_css\');

SO网友:Weston Ruter

你有一个小的拼写错误get_theme_mod() 呼叫您正在使用post-box-image 应该是什么时候post_box_image. 就像这样:

<div class="post-block" style="background-image:url(\'<?php echo esc_url( get_theme_mod( \'post_box_image\' ) ); ?>\');">
此外,在定义设置时,应指定sanitize_callback 像这样:

$wp_customize->add_setting( \'post_box_image\', array(
    \'sanitize_callback\' => function( $value ) {
        if ( ! empty( $value ) ) {
            $value = esc_url_raw( $value );
            if ( empty( $value ) ) {
                return new WP_Error( \'invalid_image\' );
            }
        }
        return $value;
    },
) );

相关推荐