add_action( 'admin_init', 'bulk_assign_product_taxonomy' );
function bulk_assign_product_taxonomy() {
// ── CONFIG ──────────────────────────────────────────────────────
$taxonomy = 'product_cat'; // or 'product_tag', custom taxonomy
$term_slug = 'your-term-slug'; // term to assign
$batch = 200; // products per batch (lower on slow hosts)
// ────────────────────────────────────────────────────────────────
if ( ! isset( $_GET['run_bulk_taxonomy'] ) ) return;
$term = get_term_by( 'slug', $term_slug, $taxonomy );
if ( ! $term ) {
wp_die( "Term '{$term_slug}' not found in '{$taxonomy}'." );
}
$offset = (int) get_transient( 'bulk_tax_offset' );
$ids = get_posts( [
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => $batch,
'offset' => $offset,
'fields' => 'ids',
] );
if ( empty( $ids ) ) {
delete_transient( 'bulk_tax_offset' );
wp_die( '✅ Done! All products assigned.' );
}
foreach ( $ids as $id ) {
// Use false to APPEND, true to REPLACE all existing terms
wp_set_object_terms( $id, $term->term_id, $taxonomy, false );
}
set_transient( 'bulk_tax_offset', $offset + $batch, HOUR_IN_SECONDS );
wp_die( "✅ Batch done: processed IDs {$offset}–" . ( $offset + $batch ) . '.
<a href="?run_bulk_taxonomy=1">▶ Run next batch</a>' );
}
访问网址:https://yoursite.com/wp-admin/?run_bulk_taxonomy=1
MYSQL方式
-- Step 1: Get the term_taxonomy_id for your term
SELECT tt.term_taxonomy_id
FROM wp_terms t
JOIN wp_term_taxonomy tt ON t.term_id = tt.term_id
WHERE t.slug = 'your-term-slug'
AND tt.taxonomy = 'product_cat';
-- Step 2: Insert relationship for ALL products at once
-- (replace 999 with your term_taxonomy_id from above)
INSERT IGNORE INTO wp_term_relationships (object_id, term_taxonomy_id)
SELECT ID, 999
FROM wp_posts
WHERE post_type = 'product'
AND post_status = 'publish';
-- Step 3: Update the term count
UPDATE wp_term_taxonomy
SET count = (
SELECT COUNT(*) FROM wp_term_relationships
WHERE term_taxonomy_id = 999
)
WHERE term_taxonomy_id = 999;
WP开发教程 WordPress导师在线教程