WPBakery短码custom-markup在admin视图无法渲染参数问题
解决WPBakery短码custom-markup中变量无法渲染的问题
我在主题中创建了一个WPBakery短码,前台输出的$heading参数可以正常显示,但在vc_map里配置的custom_markup中,无法渲染$heading变量,尝试全局变量也没用。
问题原因
vc_map初始化时,custom_markup会被静态解析并固定下来,此时短码的动态参数还未传入,直接使用PHP变量$heading自然无法获取到值。WPBakery提供了专门的占位符机制或回调函数来处理动态内容。
解决方案
方法1:使用内置占位符语法
WPBakery支持用{{param_name}}的占位符格式,自动替换对应参数的值。直接修改custom_markup的定义:
<?php // 直接定义带占位符的标记,无需ob_start $wena02_markup = '<div class="item-container"> <p>This is admin view:</p> <h4>{{heading}}</h4> </div>'; vc_map( array( 'name' => __( 'Heading' , 'wena-theme' ), 'base' => 'wena02_item', 'description' => __( 'Custom heading', 'wena-theme' ), 'content_element' => true, 'custom_markup' => $wena02_markup, 'show_settings_on_create' => true, 'params' => array( array( 'type' => 'textfield', 'heading' => __( 'Test Heading', 'wena-theme' ), 'holder' => 'div', 'param_name' => 'heading', 'description' => __( 'Heading will be displayed.', 'wena-theme' ), ), ), ) ); // 以下短码类和输出函数保持不变 if(class_exists('WPBakeryShortCodesContainer')){ class WPBSC_Wena02_Item extends WPBakeryShortCodesContainer {} } if(!function_exists('wena02_item_output')){ function wena02_item_output( $atts, $content = null){ extract(shortcode_atts( array( 'heading' => '' ), $atts )); ob_start(); ?> <div class="item-container"> <h4><?php echo $heading; ?></h4> </div> <?php return ob_get_clean(); } add_shortcode( 'wena02_item' , 'wena02_item_output' ); }
方法2:使用回调函数动态生成标记
如果需要更复杂的逻辑(比如条件判断、格式化),可以给custom_markup传入一个回调函数,函数会接收当前短码的参数数组:
<?php vc_map( array( 'name' => __( 'Heading' , 'wena-theme' ), 'base' => 'wena02_item', 'description' => __( 'Custom heading', 'wena-theme' ), 'content_element' => true, 'custom_markup' => function($atts) { // 这里可以直接使用$atts里的参数 $heading = isset($atts['heading']) ? $atts['heading'] : '默认标题'; ob_start(); ?> <div class="item-container"> <p>This is admin view:</p> <h4><?php echo esc_html($heading); ?></h4> </div> <?php return ob_get_clean(); }, 'show_settings_on_create' => true, 'params' => array( array( 'type' => 'textfield', 'heading' => __( 'Test Heading', 'wena-theme' ), 'holder' => 'div', 'param_name' => 'heading', 'description' => __( 'Heading will be displayed.', 'wena-theme' ), ), ), ) ); // 短码类和输出函数部分保持不变 if(class_exists('WPBakeryShortCodesContainer')){ class WPBSC_Wena02_Item extends WPBakeryShortCodesContainer {} } if(!function_exists('wena02_item_output')){ function wena02_item_output( $atts, $content = null){ extract(shortcode_atts( array( 'heading' => '' ), $atts )); ob_start(); ?> <div class="item-container"> <h4><?php echo $heading; ?></h4> </div> <?php return ob_get_clean(); } add_shortcode( 'wena02_item' , 'wena02_item_output' ); }
说明
- 方法1适合简单场景,直接用占位符即可实现参数替换,无需额外逻辑。
- 方法2适合需要动态处理参数的场景,比如对参数进行过滤、添加默认值或条件渲染。
内容的提问来源于stack exchange,提问作者Wenatech
相关产品推荐
相关产品推荐

