You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

定制WordPress主题:如何用Customizer API在首页动态添加短代码?

解决WordPress Customizer中动态显示短代码的问题

嘿,我来帮你搞定这个客户评价板块的短代码显示问题!你刚才的代码问题确实出在嵌套echo上——get_theme_mod()(注:你之前写的get_theme_mode是笔误,正确函数是get_theme_mod)本身就会返回你在Customizer里输入的短代码字符串,不需要再用echo包裹它,直接把它传给do_shortcode()就行。

第一步:修正模板输出代码

把你之前的错误代码:

echo do_shortcode( echo get_theme_mode('testimonials'));

替换成正确的写法:

// 获取Customizer中保存的短代码,第二个参数是默认空值,防止未设置时出错
$testimonial_shortcode = get_theme_mod( 'testimonials', '' );

// 确保短代码不为空时再输出,避免多余的空白内容
if ( ! empty( $testimonial_shortcode ) ) {
    echo do_shortcode( $testimonial_shortcode );
}

第二步:确保Customizer配置的关键细节(补充)

虽然你说Customizer相关配置已完成,但这里提一个容易忽略的关键点:要确保你的设置使用了允许短代码的 sanitize 回调函数,不然输入的短代码可能会被WordPress过滤掉。如果你的注册代码还没处理这一点,可以参考下面的示例:

function mytheme_customize_register( $wp_customize ) {
    // 添加客户评价设置板块
    $wp_customize->add_section( 'testimonials_section', array(
        'title'       => __( '客户评价板块', 'mytheme' ),
        'priority'    => 30,
        'description' => __( '输入你的客户评价短代码,它会自动显示在首页对应位置', 'mytheme' ),
    ) );

    // 注册短代码设置项
    $wp_customize->add_setting( 'testimonials', array(
        'default'           => '',
        // 使用wp_kses_post允许短代码和合法HTML标签,同时过滤不安全内容
        'sanitize_callback' => 'wp_kses_post',
    ) );

    // 添加短代码输入控件(用textarea更适合长/多行短代码)
    $wp_customize->add_control( 'testimonials_control', array(
        'label'    => __( '客户评价短代码', 'mytheme' ),
        'section'  => 'testimonials_section',
        'settings' => 'testimonials',
        'type'     => 'textarea',
    ) );
}
add_action( 'customize_register', 'mytheme_customize_register' );

额外小提示

  • 如果你用的是单行短代码,也可以把控件类型改成text,但textarea对多参数短代码的适配性更强;
  • 测试时可以先输入一个简单的短代码(比如[gallery])验证渲染效果,再替换成你的客户评价专用短代码。

内容的提问来源于stack exchange,提问作者Smurfy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:15:16