
本文介绍通过 php 脚本安全、高效地批量修改 woocommerce 商品所属分类,支持通过 url 触发(如 domain.de/start.php?update_cats=yes),将所有属于旧分类(如 cat2)的商品自动重新归类到新分类(如 cat4)。
本文介绍通过 php 脚本安全、高效地批量修改 woocommerce 商品所属分类,支持通过 url 触发(如 domain.de/start.php?update_cats=yes),将所有属于旧分类(如 cat2)的商品自动重新归类到新分类(如 cat4)。
在 WooCommerce 项目维护中,常需对大量商品进行分类结构调整(例如品牌迁移、类目重构或 SEO 优化)。手动逐个编辑效率低下且易出错,而使用 WordPress 原生函数结合条件触发的脚本可实现精准、可控的批量更新。
以下是一个生产环境可用的轻量级解决方案,保存为 start.php 放置于网站根目录(如 domain.de/start.php),通过 GET 参数安全触发:
<?php // start.php —— WooCommerce 批量分类更新脚本
define('WP_USE_THEMES', false);
require_once($_SERVER['DOCUMENT_ROOT'] . '/wp-load.php');
// 仅当明确传入 ?update_cats=yes 时执行,防止误触发
if (isset($_GET['update_cats']) && $_GET['update_cats'] === 'yes') {
// 验证用户权限(强烈建议:仅限管理员)
if (!current_user_can('manage_woocommerce')) {
wp_die('权限不足:仅管理员可执行此操作。');
}
// 设置超时与内存限制(应对大量商品)
set_time_limit(300);
ini_set('memory_limit', '512M');
// 【核心逻辑】查找所有属于旧分类(如 'cat2')的商品,并替换为新分类(如 'cat4')
$old_category_slug = 'cat2'; // ✅ 替换为你实际的旧分类 slug(非名称!)
$new_category_slug = 'cat4'; // ✅ 替换为你实际的新分类 slug
$args = array(
'status' => 'publish', // 仅处理已发布商品
'limit' => -1, // 获取全部匹配商品(注意:大数据量建议分页处理)
'category' => array($old_category_slug),
'return' => 'ids', // 仅返回商品 ID,减少内存占用
);
$product_ids = wc_get_products($args);
if (empty($product_ids)) {
echo "<p>✅ 未找到属于分类 '{$old_category_slug}' 的商品。</p>";
exit;
}
$success_count = 0;
foreach ($product_ids as $product_id) {
// 注意:wp_set_object_terms 第三个参数设为 true 表示「追加」,false 表示「替换」
// 此处使用 false,确保完全移除旧分类,仅保留新分类(若需保留其他原有分类,请改用 wp_remove_object_terms + wp_set_object_terms 组合)
$result = wp_set_object_terms($product_id, $new_category_slug, 'product_cat', false);
if (!is_wp_error($result)) {
$success_count++;
}
}
echo "<p>✅ 批量更新完成!共 {$success_count}/" . count($product_ids) . " 个商品已将分类从 '{$old_category_slug}' 更新为 '{$new_category_slug}'。</p>";
echo "<p><a href="%22%20.%20esc_url(wp_get_referer()%20?:%20home_url())%20.%20%22">← 返回首页</a></p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/ai/2492" title="蕉点AI"><img
src="https://img.php.cn/upload/ai_manual/001/246/273/176844717120623.png" alt="蕉点AI" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/ai/2492" title="蕉点AI" class="overflowclass">蕉点AI</a>
<p class="overflowclass">一款AI图像与设计工具,主要用于AI电商商品图生成平台 | 智能商品素材制作工具,适合需要提升相关任务效率的用户。</p>
</div>
<a rel="nofollow" href="/ai/2492" title="蕉点AI" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>";
exit;
}
// 默认页面展示说明(防止直接访问无参数时暴露逻辑)
?>
<title>WooCommerce 分类批量更新工具</title><h1>?️ WooCommerce 商品分类批量更新</h1>
<p><strong>用途:</strong>将所有属于指定旧分类的商品,统一迁移到新分类。</p>
<p><strong>使用方法:</strong>访问 <code><?php echo esc_url(home_url('/start.php?update_cats=yes')); ?></code> 并确认执行。</p>
- ⚠️ 重要前提:请确保
cat2和cat4是已存在的分类 slug(可在后台「产品 → 分类」中鼠标悬停查看 URL 中的taxonomy=product_cat&tag_ID=xxx对应 slug) - ? 脚本自动校验管理员权限,非授权用户无法执行
- ⏱️ 大于 500 个商品时,建议在服务器 CLI 环境运行或拆分批次(可添加 offset/limit 分页逻辑)
- ? 执行前请务必备份数据库(推荐使用 WP Time Capsule 或 All-in-One WP Migration)
关键注意事项:
- Slug 而非名称:wc_get_products() 的 category 参数必须传入分类的 slug(如 t-shirts),而非中文名称(如 “T恤”)。可通过 WordPress 后台分类列表 URL 或数据库 wp_terms 表确认。
- 分类覆盖 vs 追加:本脚本使用 wp_set_object_terms(..., ..., 'product_cat', false) 实现「完全替换」——即移除所有原分类,仅设置新分类。若需保留其他已有分类(如同时保留 cat1 和 cat3),应改用 wp_remove_object_terms($id, $old_slug, 'product_cat') + wp_set_object_terms($id, $new_slug, 'product_cat', true)。
- 性能与安全:脚本内置权限校验、超时控制与内存优化;生产环境建议添加 nonce 验证或 IP 白名单进一步加固。
-
验证结果:执行后可在 WordPress 后台「产品 → 所有产品」筛选对应分类,或通过 SQL 快速验证:
SELECT p.ID, p.post_title FROM wp_posts p JOIN wp_term_relationships tr ON p.ID = tr.object_id JOIN wp_term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id JOIN wp_terms t ON tt.term_id = t.term_id WHERE p.post_type = 'product' AND p.post_status = 'publish' AND t.slug = 'cat4';
掌握此方法,你即可在数秒内完成数百乃至数千商品的分类重构,大幅提升 WooCommerce 运维效率与准确性。










