如何在WooCommerce中基于PHP会话变量过滤指定restriction_id的产品?
WooCommerce 基于会话变量过滤指定restriction_id的产品
嘿,我来帮你搞定这个产品过滤需求!要实现基于PHP会话里的restriction_id值,排除对应属性产品的功能,得先明确:WooCommerce的产品属性会被注册为自定义分类法,前缀是pa_,所以你的restriction_id属性对应的分类法是pa_restriction_id。
下面是完整的代码实现,直接替换你原来的起始代码即可:
// Define the woocommerce_product_query callback function function action_woocommerce_product_query( $q, $instance ) { // 确保PHP会话已启动,避免未初始化的报错 if ( ! session_id() ) { session_start(); } // 从会话中获取restriction_id值,同时转为整数保证安全性 $restriction_id = isset( $_SESSION['restriction_id'] ) ? intval( $_SESSION['restriction_id'] ) : 0; // 仅当会话中有有效ID时执行过滤逻辑 if ( $restriction_id > 0 ) { // 获取当前查询已有的tax_query规则(如果存在) $tax_query = $q->get( 'tax_query' ) ?: array(); // 添加新的过滤规则:排除pa_restriction_id属性值匹配会话ID的产品 $tax_query[] = array( 'taxonomy' => 'pa_restriction_id', // WooCommerce产品属性的固定前缀格式 'field' => 'term_id', // 按属性值的术语ID匹配 'terms' => $restriction_id, 'operator' => 'NOT IN', // 核心:排除匹配的产品 ); // 更新查询的tax_query参数 $q->set( 'tax_query', $tax_query ); } }; // Add the action add_action( 'woocommerce_product_query', 'action_woocommerce_product_query', 10, 2 );
关键细节说明:
- 会话初始化检查:先判断会话是否启动,避免直接调用
$_SESSION时出现未初始化的错误 - 变量安全处理:用
intval()把会话值转为整数,避免非数字值带来的查询异常或安全风险 - Tax Query逻辑:因为WooCommerce产品属性本质是分类法,所以用
tax_query而非meta_query;operator设为NOT IN就能精准排除目标产品 - 兼容原有规则:保留查询中原有的
tax_query配置,不会覆盖其他已有的产品过滤条件
这样当你把会话变量$_SESSION['restriction_id']设为35时,所有restriction_id属性值为35的产品就会被自动从查询结果中排除啦。
内容的提问来源于stack exchange,提问作者Richard Thompson
相关产品推荐
相关产品推荐

