为Elementor添加产品类型显示子条件的技术实现问题
Elementor 自定义产品类型显示条件(修复子条件层级问题)
问题说明
要给Elementor主题构建器添加按产品类型筛选的自定义显示条件,现有代码已能注册主条件,但所有子条件都直接混在主条件列表中,没有形成嵌套层级,需要调整代码让子条件归属于主条件下。
修正后的完整代码
<?php if ( ! defined( 'ABSPATH' ) ) { exit; // 直接访问时退出 } use ElementorPro\Modules\ThemeBuilder\Conditions\Condition_Base; class Product_Type_Condition extends Condition_Base { public function get_name() { return 'product_type_condition'; } public function get_label() { return __( '产品类型', 'text-domain' ); } public function get_type() { return 'product'; } // 关键:添加该方法定义子条件,实现层级嵌套 public function get_child_conditions() { $child_conditions = []; // 获取所有WooCommerce产品类型 $product_types = wc_get_product_types(); foreach ( $product_types as $type_key => $type_label ) { $child_conditions[] = new Product_Type_Sub_Condition( $type_key, $type_label ); } return $child_conditions; } // 主条件验证:只要是产品页面就通过 public function check( $args ) { return is_product(); } } class Product_Type_Sub_Condition extends Condition_Base { private $product_type_key; private $product_type_label; public function __construct( $product_type_key, $product_type_label ) { $this->product_type_key = $product_type_key; $this->product_type_label = $product_type_label; } public function get_name() { return 'product_type_sub_condition_' . $this->product_type_key; } public function get_label() { return $this->product_type_label; } // 子条件验证:判断当前产品类型是否匹配 public function check( $args ) { if ( ! is_product() ) { return false; } $product = wc_get_product( get_the_ID() ); return $product && $product->get_type() === $this->product_type_key; } } add_action( 'elementor/theme/register_conditions', 'register_custom_product_type_condition' ); function register_custom_product_type_condition( $conditions_manager ) { $conditions_manager->register( new Product_Type_Condition() ); }
关键修改说明
- 添加
get_child_conditions方法:在主条件类Product_Type_Condition中新增该方法,通过wc_get_product_types()获取所有WooCommerce产品类型,动态生成对应的子条件实例,Elementor会自动将子条件嵌套在主条件下方,形成层级结构。 - 完善
check方法:- 主条件的
check仅验证当前是否为产品页面,确保主条件的范围正确。 - 子条件的
check获取当前产品实例,判断其类型是否与子条件对应的类型匹配。
- 主条件的
- 简化注册流程:无需单独注册每个子条件,注册主条件后,Elementor会通过
get_child_conditions自动加载所有子条件。
内容的提问来源于stack exchange,提问作者GU Shap
相关产品推荐
相关产品推荐

