星期一 , 14 4 月 2025

将任何数据的product.csv转换成wordpress

将任何数据的product.csv转换成wordpress

<?php
/**
 * Custom Product CSV Importer
 * Handles custom taxonomy 'product_category' and specific meta fields
 */

// Register the admin menu
add_action('admin_menu', 'register_product_import_page');
function register_product_import_page() {
    add_menu_page(
        'Import Products', 
        'Import Products',
        'manage_options',
        'product-csv-import',
        'render_product_import_page'
    );
}

// Render the import page
function render_product_import_page() {
    ?>
    <div class="wrap">
        <h1>Import Products from CSV</h1>
        <p>CSV should include these columns: title, description, cateid, sku, price, summary, alias</p>
        <form method="post" enctype="multipart/form-data">
            <input type="file" name="product_csv" accept=".csv" required>
            <?php wp_nonce_field('import_products_nonce', 'import_nonce'); ?>
            <input type="submit" name="import_products" class="button button-primary" value="Import Products">
        </form>
    </div>
    <?php

    if (isset($_POST['import_products']) && check_admin_referer('import_products_nonce', 'import_nonce')) {
        handle_product_csv_import();
    }
}

// Handle the CSV import
function handle_product_csv_import() {
    if (!current_user_can('manage_options')) {
        wp_die('Unauthorized access');
    }

    $file = $_FILES['product_csv'];
    
    if ($file['error'] !== UPLOAD_ERR_OK) {
        echo '<div class="error"><p>Error uploading file.</p></div>';
        return;
    }

    $handle = fopen($file['tmp_name'], 'r');
    if (!$handle) {
        echo '<div class="error"><p>Error reading file.</p></div>';
        return;
    }

    // Get headers
    $headers = fgetcsv($handle);
    $imported = 0;
    $errors = 0;

    // Process each row
    while (($data = fgetcsv($handle)) !== FALSE) {
        $product_data = array_combine($headers, $data);
        
        // Create post object
        $post_data = array(
            'post_title'    => wp_strip_all_tags($product_data['title']),
            'post_content'  => $product_data['description'],
            'post_status'   => 'publish',
            'post_type'     => 'product'
        );

        // Insert the post
        $post_id = wp_insert_post($post_data);

        if (!is_wp_error($post_id)) {
            // Set product category
            if (!empty($product_data['cateid'])) {
                wp_set_object_terms($post_id, intval($product_data['cateid']), 'product_category');
            }

            // Save custom meta fields
            $meta_fields = array('sku', 'price', 'summary', 'alias');
            foreach ($meta_fields as $field) {
                if (isset($product_data[$field])) {
                    update_post_meta($post_id, '_product_' . $field, sanitize_text_field($product_data[$field]));
                }
            }
            
            $imported++;
        } else {
            $errors++;
        }
    }

    fclose($handle);

    echo '<div class="updated"><p>Import completed. Imported: ' . $imported . ' products. Errors: ' . $errors . '</p></div>';
}

// Register custom post type for products
add_action('init', 'register_custom_product_post_type');
function register_custom_product_post_type() {
    // Register Custom Post Type
    register_post_type('product', array(
        'labels' => array(
            'name' => 'Products',
            'singular_name' => 'Product'
        ),
        'public' => true,
        'has_archive' => true,
        'supports' => array('title', 'editor', 'thumbnail'),
        'menu_icon' => 'dashicons-cart'
    ));

    // Register Custom Taxonomy
    register_taxonomy('product_category', 'product', array(
        'labels' => array(
            'name' => 'Product Categories',
            'singular_name' => 'Product Category'
        ),
        'hierarchical' => true,
        'show_ui' => true,
        'show_admin_column' => true,
        'query_var' => true,
        'rewrite' => array('slug' => 'product-category')
    ));
}

// Add custom columns to admin list
add_filter('manage_product_posts_columns', 'set_custom_product_columns');
function set_custom_product_columns($columns) {
    $columns['sku'] = 'SKU';
    $columns['price'] = 'Price';
    $columns['product_category'] = 'Category';
    return $columns;
}

// Fill custom columns with data
add_action('manage_product_posts_custom_column', 'custom_product_column', 10, 2);
function custom_product_column($column, $post_id) {
    switch ($column) {
        case 'sku':
            echo get_post_meta($post_id, '_product_sku', true);
            break;
        case 'price':
            echo get_post_meta($post_id, '_product_price', true);
            break;
        case 'product_category':
            $terms = get_the_terms($post_id, 'product_category');
            if ($terms && !is_wp_error($terms)) {
                $category_names = array();
                foreach ($terms as $term) {
                    $category_names[] = $term->name;
                }
                echo implode(', ', $category_names);
            }
            break;
    }
}