首先上传分类表,添加分类表的id作为单独字段,比方说original_id
function import_product_categories($csv_file) {
$categories = array(); // Store original ID to new term ID mapping
// Open and parse CSV file
$handle = fopen($csv_file, 'r');
// Skip header row
fgetcsv($handle);
while (($data = fgetcsv($handle)) !== FALSE) {
$original_id = $data[0]; // Original category ID from old system
$name = $data[1];
$description = $data[2]; // If applicable
// Check if category already exists
$existing = term_exists($name, 'product_category');
if (!$existing) {
// Create new category
$new_term = wp_insert_term(
$name,
'product_category',
array(
'description' => $description
)
);
if (!is_wp_error($new_term)) {
// Store mapping between original ID and new WordPress term ID
update_term_meta($new_term['term_id'], 'original_category_id', $original_id);
$categories[$original_id] = $new_term['term_id'];
}
} else {
// Category exists, update mapping
update_term_meta($existing['term_id'], 'original_category_id', $original_id);
$categories[$original_id] = $existing['term_id'];
}
}
fclose($handle);
return $categories; // Return the mapping for potential reuse
}
上传产品(文章表)然后链接到分类
function import_products($csv_file) {
// Open and parse CSV file
$handle = fopen($csv_file, 'r');
// Skip header row
fgetcsv($handle);
while (($data = fgetcsv($handle)) !== FALSE) {
$title = $data[0];
$description = $data[1];
$price = $data[2]; // If applicable
$original_category_id = $data[3]; // This is your "cateid" from the original database
// Create the product
$product_args = array(
'post_title' => $title,
'post_content' => $description,
'post_status' => 'publish',
'post_type' => 'product'
);
$product_id = wp_insert_post($product_args);
if (!is_wp_error($product_id)) {
// Add price or other product meta
update_post_meta($product_id, '_price', $price);
// Store the original category ID as post meta (for reference)
update_post_meta($product_id, 'original_category_id', $original_category_id);
// Find the WordPress term ID using the original category ID
$args = array(
'taxonomy' => 'product_category',
'meta_key' => 'original_category_id',
'meta_value' => $original_category_id,
'hide_empty' => false
);
$terms = get_terms($args);
if (!empty($terms) && !is_wp_error($terms)) {
$term_ids = array();
foreach ($terms as $term) {
$term_ids[] = $term->term_id;
}
// Set the product category
wp_set_object_terms($product_id, $term_ids, 'product_category');
}
}
}
fclose($handle);
}
全部导入
function run_import() {
// Step 1: Import categories first
$category_mapping = import_product_categories('path/to/categories.csv');
// Step 2: Import products
import_products('path/to/products.csv');
echo "Import completed successfully!";
}
// Run the import
add_action('admin_init', 'run_import');