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

如何将主题修改值设为短代码默认属性?

解决方法:将Theme Mod设为短代码默认属性

嘿,这事儿其实挺简单的!咱们只需要在短代码的处理函数里,用WordPress内置的shortcode_atts()来合并用户传入的属性和默认值,把get_theme_mod('primary_location')设为location属性的默认值就可以了。

完整的短代码实现示例

// 注册自定义地图短代码
function custom_map_shortcode( $atts ) {
    // 定义短代码属性的默认值,这里把theme mod作为location的默认值
    $default_atts = array(
        'location' => get_theme_mod( 'primary_location', '默认兜底地址' ), // 第二个参数是兜底值,防止theme mod为空
        'height'   => '500',
        'width'    => '100%',
        'zoom'     => '13'
    );

    // 合并用户传入的属性和默认值,用户传入的属性会覆盖默认值
    $atts = shortcode_atts( $default_atts, $atts );

    // 对属性值进行安全转义,避免XSS风险
    $safe_location = esc_attr( $atts['location'] );
    $safe_height = esc_attr( $atts['height'] );
    $safe_width = esc_attr( $atts['width'] );
    $safe_zoom = esc_attr( $atts['zoom'] );

    // 拼接并返回iframe代码
    return '<iframe width="' . $safe_width . '" height="' . $safe_height . '" id="gmap_canvas" src="https://maps.google.com/maps?q=' . $safe_location . '&t=&z=' . $safe_zoom . '&ie=UTF8&iwloc=&output=embed" frameborder="0" scrolling="no" marginheight="0" marginwidth="0"></iframe>';
}
add_shortcode( 'custom_map', 'custom_map_shortcode' );

关键细节说明

  • 默认值优先级:当用户使用短代码时,如果不传location属性,就会自动使用get_theme_mod('primary_location')的值;如果用户传入了location(比如[custom_map location="上海外滩"]),就会优先使用用户指定的地址。
  • 安全处理:用esc_attr()转义所有属性值,这是WordPress开发的最佳实践,能有效防止跨站脚本攻击(XSS)。
  • 兜底值:get_theme_mod()的第二个参数是兜底地址,万一主题修改项没有设置值,短代码也不会出错。

使用方式

  • 默认调用(使用theme mod的地址):
    [custom_map]
    
  • 自定义属性(覆盖默认值):
    [custom_map location="广州塔" height="600" zoom="14"]
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:35:21