我目前正在处理我的第一个主题,并试图允许用户在自定义程序中编辑一些文本。
基本上,我已经获得了用户在定制器中写入的文本,以在前端显示,但默认文本没有显示,我不知道如何让它显示。
下面是我在customizer上输入的代码。php文件
$wp_customize->add_section(\'home_header\', array(
\'title\' => __(\'Home Header\', \'sincere\'),
\'description\' => \'\',
\'priority\' => 70,
));
$wp_customize->add_setting( \'home_header_title\', array(
\'capability\' => \'edit_theme_options\',
\'default\' => __(\'Clean. Simple. Sincere\', \'sincere\'),
\'sanitize_callback\' => \'sanitize_text_field\',
) );
$wp_customize->add_control( \'home_header_title\', array(
\'type\' => \'text\',
\'section\' => \'home_header\', // Add a default or your own section
\'label\' => __( \'Header Text\' ),
) );
这是我放在头版的代码。php文件尝试显示文本。
<section class="feature-image feature-image-home feature-image-default-alt"
data-type="background" data-speed="2">
<h1 class="entry-title"><?php echo get_theme_mod(\'home_header_title\'); ?
></h1>
</section>
提前感谢您的帮助!
SO网友:Jacob Peattie
注册设置时设置默认值并不会使其成为输出时的默认值,而是使其成为打开customiser时的默认值。要在打开/保存自定义程序之前提供默认值,请将其作为第二个参数传递给get_theme_mod()
:
<?php echo get_theme_mod(\'home_header_title\', __(\'Clean. Simple. Sincere\', \'sincere\') ); ?>
这可能很烦人,因为必须将默认值写两次。因此,您可以做的一件事是创建一个返回默认值的函数,并在这两个位置使用它。
函数如下所示:
function sincere_get_theme_default( $setting ) {
$defaults = array(
\'home_header_title\' => __( \'Clean. Simple. Sincere\', \'sincere\' ),
);
return $defaults[$setting];
}
然后,在注册设置时将其作为默认值调用:
$wp_customize->add_setting( \'home_header_title\', array(
\'capability\' => \'edit_theme_options\',
\'default\' => sincere_get_theme_default( \'home_header_title\' ),
\'sanitize_callback\' => \'sanitize_text_field\',
) );
也是的默认参数
get_theme_mod()
:
<?php echo get_theme_mod( \'home_header_title\', sincere_get_theme_default( \'home_header_title\' ) ); ?>
SO网友:Jitender Singh
在我这边,您的代码运行良好。如果文本自定义程序部分中未显示默认文本,请尝试更改设置id,或者简单地尝试此代码和硬引用浏览器(ctrl+F5
).不要忘记尝试更改设置id。
add_action( \'customize_register\', \'mytheme_text_customizer\' );
function mytheme_text_customizer($wp_customize){
$wp_customize->add_section(\'home_header\', array(
\'title\' => __(\'Home Header\', \'sincere\'),
\'description\' => \'\',
\'priority\' => 70,
));
$wp_customize->add_setting( \'home_header_title\', array(
\'capability\' => \'edit_theme_options\',
\'default\' => __(\'Clean. Simple. Sincere\', \'sincere\'),
\'sanitize_callback\' => \'sanitize_text_field\',
) );
$wp_customize->add_control( \'home_header_title\', array(
\'type\' => \'text\',
\'section\' => \'home_header\', // Add a default or your own section
\'label\' => __( \'Header Text\' )
) );
}