如何在WordPress的functions.php中排除查询中的指定产品分类?
解决方案:排除指定产品分类的缺货商品处理
要让你的代码跳过某个产品分类的商品,只需在WP_Query的查询参数里添加tax_query规则,过滤掉目标分类即可。具体操作如下:
1. 确定要排除的分类标识
你需要知道目标分类的slug(别名)或者ID,二选一即可。比如:
- 分类slug:假设是
special-items - 分类ID:假设是
15
2. 修改查询参数
在原代码的$params数组中,添加tax_query配置,用NOT IN操作符排除指定分类:
$params = [ 'posts_per_page' => -1, 'post_type' => 'product', 'post_status' => 'publish', // 新增:排除指定产品分类 'tax_query' => [ [ 'taxonomy' => 'product_cat', // WooCommerce产品分类的分类法 'field' => 'slug', // 用slug还是id,对应下面的terms值 'terms' => 'special-items', // 替换成你要排除的分类slug或ID 'operator' => 'NOT IN', // 表示排除该分类下的商品 ], ], ];
如果用分类ID,只需把'field'改成'id','terms'改成对应的ID即可:
'field' => 'id', 'terms' => 15,
3. 完整修改后的代码
add_action('admin_init', 'woo_moveoutofstocktodraft'); function woo_moveoutofstocktodraft() { $current_user = wp_get_current_user(); // 非管理员用户直接返回 if (!user_can($current_user, 'administrator')) { return; } $params = [ 'posts_per_page' => -1, 'post_type' => 'product', 'post_status' => 'publish', // 新增:排除指定产品分类 'tax_query' => [ [ 'taxonomy' => 'product_cat', 'field' => 'slug', // 可替换为'id' 'terms' => 'special-items', // 替换为你的目标分类slug或ID 'operator' => 'NOT IN', ], ], ]; $wc_query = new WP_Query($params); if ($wc_query->have_posts()) : while ($wc_query->have_posts()) : $wc_query->the_post(); $product_id = get_the_ID(); $product = wc_get_product($product_id); // 缺货则改为草稿状态 if (!$product->is_in_stock()) { $post = array( 'ID' => $product_id, 'post_status' => 'draft' ); wp_update_post($post); } endwhile; wp_reset_postdata(); endif; }
这样修改后,代码就会自动跳过你指定分类下的所有商品,不会将它们的状态改为草稿。
内容的提问来源于stack exchange,提问作者Simulator88
相关产品推荐
相关产品推荐

