Elementor Pro模板内元素自定义显示条件(含$_GET参数判断)咨询
为Elementor元素/区块/小部件添加基于$_GET参数的自定义显示条件
Elementor Pro的模板显示条件无法直接作用于单个元素,要实现基于特定$_GET参数的元素显示控制,需要通过自定义代码扩展Elementor的功能,具体步骤如下:
1. 注册自定义显示条件控件
将以下代码添加到主题的functions.php文件或自定义插件中,用于在Elementor编辑器的元素设置面板里新增一个自定义控件,让你指定要检查的$_GET参数名:
add_action( 'elementor/controls/register', 'register_get_param_control' ); function register_get_param_control( $controls_manager ) { class Elementor_Control_Get_Param extends \Elementor\Base_Data_Control { public function get_type() { return 'get_param_check'; } protected function get_default_settings() { return [ 'label' => '检查$_GET参数', 'placeholder' => '输入要检查的参数名,如:utm_source', ]; } public function content_template() { ?> <div class="elementor-control-field"> <label class="elementor-control-title">{{{ data.label }}}</label> <div class="elementor-control-input-wrapper"> <input type="text" placeholder="{{ data.placeholder }}" data-setting="{{ data.name }}"> </div> </div> <?php } } $controls_manager->register( new Elementor_Control_Get_Param() ); } // 为所有Elementor元素添加这个控件 add_action( 'elementor/element/before_section_end', 'add_get_param_control_to_elements', 10, 3 ); function add_get_param_control_to_elements( $element, $section_id, $args ) { // 针对元素的"高级"设置面板添加控件 if ( 'section_advanced' === $section_id ) { $element->add_control( 'required_get_param', [ 'type' => 'get_param_check', 'label' => '仅当存在指定$_GET参数时显示', 'description' => '留空则不启用此条件', ] ); } }
2. 实现显示条件逻辑
继续添加以下代码,用于在前端渲染元素前检查$_GET参数是否存在,不存在则隐藏元素:
add_action( 'elementor/frontend/element/before_render', 'check_get_param_condition', 10, 1 ); function check_get_param_condition( $element ) { $settings = $element->get_settings_for_display(); $required_param = $settings['required_get_param'] ?? ''; if ( ! empty( $required_param ) && ! isset( $_GET[ $required_param ] ) ) { // 不满足条件,停止渲染元素 $element->set_visible( false ); } }
使用方法
- 保存上述代码后,刷新Elementor编辑器;
- 编辑需要设置条件的元素/区块/小部件,打开「高级」设置面板;
- 在「仅当存在指定$_GET参数时显示」输入框中填写要检查的参数名(比如
promo); - 保存页面,前端只有当URL中包含
?promo=xxx(参数值可任意)时,该元素才会显示。
注意事项
- 代码需添加到子主题的
functions.php中,避免主题更新时丢失; - 若需要更复杂的判断(比如检查参数值是否匹配),可修改
check_get_param_condition函数中的逻辑,例如添加$_GET[ $required_param ] === '特定值'的判断。
内容的提问来源于stack exchange,提问作者ACJ
相关产品推荐
相关产品推荐

