Elementor API:基于SELECT2控件实现自定义控件的条件显示问题
Elementor多选SELECT2控件条件显示失效的解决办法
Elementor原生条件系统对多选SELECT2返回的数组值支持有限,默认的in运算符无法正确匹配数组中的元素,你可以通过以下两种方式解决:
方法一:使用自定义回调函数判断条件
直接在conditions中添加callback,手动校验多选控件的选中值:
$this->add_control( 'grid_hr', [ 'label' => esc_html__( 'Grid options', 'text-domain' ), 'type' => Controls_Manager::HEADING, 'separator' => 'before', 'conditions' => [ 'callback' => function( $args ) { // 获取当前widget的model控件值 $selected_models = $args['widget']->get_settings_for_display( 'model' ); // 判断是否包含'grid'选项 return is_array( $selected_models ) && in_array( 'grid', $selected_models ); }, ], ] );
方法二:注册自定义条件运算符(进阶)
如果需要多次复用这类判断,可以扩展Elementor的条件运算符,添加一个专门用于数组包含的判断:
// 在插件初始化或widget注册前添加 add_action( 'elementor/controls/conditions/register_operators', function( $conditions_manager ) { $conditions_manager->register_operator( 'array_contains', [ 'label' => esc_html__( 'Array Contains', 'text-domain' ), 'callback' => function( $value, $compare_value ) { return is_array( $value ) && in_array( $compare_value, $value ); }, ] ); } ); // 之后在控件条件中使用 $this->add_control( 'grid_hr', [ 'label' => esc_html__( 'Grid options', 'text-domain' ), 'type' => Controls_Manager::HEADING, 'separator' => 'before', 'conditions' => [ 'terms' => [ [ 'name' => 'model', 'operator' => 'array_contains', 'value' => 'grid', ], ], ], ] );
注意事项
- 确保
model控件的multiple属性设为true,且frontend_available为true(你已经配置正确) - 使用
get_settings_for_display而非直接取$args['settings'],确保获取到的是处理后的最终值
内容的提问来源于stack exchange,提问作者Lucas M. Falbo
相关产品推荐
相关产品推荐

