Import products in WooCommerce with categories

49 Views Asked by At

I have been trying for weeks to import products, either from a csv or from an xml. I can import data such as title price sku image, but I cannot import the categories. neither separately, nor together with the same function

the idea of ​​this is to automate it with a daily cronjob

function import_products_from_csv() {
    // Path of the CSV file on your server
    $local_file_path = WP_CONTENT_DIR . '/../products.csv';

$args = array(
        'post_type' => 'product',
        'posts_per_page' => -1,
    );

    $products = get_posts($args);

    // Delete each product
    foreach ($products as $product) {
wp_delete_post($product->ID, true); // The second parameter (true) will force the permanent deletion of the product.
    }

    // Check if the CSV file exists
    if (file_exists($local_file_path)) {
        // Open the CSV file for reading
        if (($handle = fopen($local_file_path, 'r')) !== false) {
// Ignore the first row (header)
            $header = fgetcsv($handle, 1000, ';');

            while (($data = fgetcsv($handle, 1000, ';')) !== false) {
                // Create a new product in WooCommerce
                $product = array(
                    'post_title' => $data[1],
// Adjust the position according to your CSV file
                   // 'post_content' => $data[2], // Adjust the position according to your CSV file
                  // 'post_excerpt' => $data[3], // Adjust the position according to your CSV file
'post_type' => 'product',
                    'post_status' => 'publish',
                );
$product_id = wp_insert_post($product);

// Assign SKU and price to the product
if ($product_id) {
update_post_meta($product_id, '_sku', $data[0]); // Adjust the position according to your CSV file
update_post_meta($product_id, '_regular_price', $data[2]); // Adjust the position according to your CSV file
update_post_meta($product_id, '_price', $data[2]);
// Force product cache refresh
wp_cache_delete($product_id, 'post_meta');
}


                // Assign categories to the product
             if (!empty($data[4])) {
$categories = explode(',', $data[4]);
//$result = wp_set_post_terms($product_id, $categories, 'productcategory');
//$result = wp_set_post_terms($product_id, $categories, 'product_cat');
$result = wp_set_object_terms($product_id, $categories, 'productcategory');
    
//var_dump($categories); // Verify that $categories has the expected categories.
//var_dump($product_id); // Verify that $product_id has the correct product ID.


/*if (taxonomy_exists('Pillows')) {
// The 'productcategory' taxonomy exists, you can use it in your code.
$result = wp_set_object_terms($product_id, $categories, 'Pillows');
} else {
// The taxonomy 'productcategory' does not exist, display an error message, or take the appropriate action.
echo 'The taxonomy "pillows" is not registered.';
}

if (is_wp_error($result)) {
echo 'Error assigning categories: ' . $result->get_error_message();
} else {
echo 'Categories assigned correctly.';
}*/
}

//
 if (!empty($data[3])) { // Adjust the position according to your CSV file
    $image_url = $data[3]; // Adjust the position according to your CSV file

    // Calculate a unique hash based on the image URL
    $image_hash = md5($image_url);

    // Search for an image with the same hash in the media library
$image_query = new WP_Query(array(
        'post_type' => 'attachment',
        'post_status' => 'any',
        'posts_per_page' => 1,
        'meta_query' => array(
            array(
                'key' => 'hash_image',
                'value' => $image_hash,
            ),
        ),
    ));

    if ($image_query->have_posts()) {
// The image already exists in the media library
        $image_id = $image_query->posts[0]->ID;
    } else {
        // The image does not exist in the media library, proceed to import it

        // Get the file name from the URL
        $file_name = basename($image_url);
// Local path where to save the image in the 'uploads' folder
        $local_path = wp_upload_dir()['path'] . '/' . $file_name;

        // Download the image from the URL and save it to the 'uploads' folder
        $image_content = file_get_contents($image_url);

        if ($content_image !== false) {
file_put_contents($local_path, $content_image);

            // Add the image to the media library
            $attachment = array(
                'post_title' => sanitize_file_name($file_name),
                'post_mime_type' => wp_check_filetype($file_name)['type'],
                'post_status' => 'inherit'
);

            $image_id = wp_insert_attachment($attachment, $local_path);

            if (!is_wp_error($image_id)) {
                // Generate metadata and update attachment information
                require_once(ABSPATH . 'wp-admin/includes/image.php');
$image_metadata = wp_generate_attachment_metadata($image_id, $local_path);
                wp_update_attachment_metadata($image_id, $image_metadata);

                // Associate the unique hash to the image
                update_post_meta($image_id, 'image_hash', $image_hash);
            } else {
echo "Error adding image to media library: " . $image_id->get_error_message();
            }
        } else {
            echo "Error downloading image from URL: " . $image_url;
        }
    }
// Assign the uploaded image (either existing or newly imported) to your product (adjust $product_id as necessary)
    set_post_thumbnail($product_id, $image_id);
}




            }

            fclose($handle);
            echo "Products successfully imported from CSV.";
        } else {
echo "Error opening CSV file.";
        }
    } else {
        echo "CSV file does not exist.";
    }
}

// Call the function to import products from CSV if any condition is met (you can define it according to your needs)
if (isset($_GET['import_products']) && $_GET['import_products'] == '1') {
import_products_from_csv();
}

I have left commented attempts, so you know where I wanted to go. I hope to know what the steps to follow are, if I have to divide it into stages or I can do it in the same function

Update attempts

I'm trying to import the product categories so they match, but I don't know if I'm on the right track

but this is not working either

the content of the csv

pillows, Bibs and accessories, Pigs, With light, rabbits, Cats

 function import_categories_from_csv() {
    // CSV file path
    $local_file_path = WP_CONTENT_DIR . '/../only_categories.csv';

    // Check if the file exists
    if (file_exists($local_file_path)) {
        // Read the CSV file
        $lines = file($local_file_path);
        if ($lines !== false) {
foreach ($lines as $line) {
                // Clear and split the line at the delimiter
                $data = str_getcsv(trim($line), ";");

                // Get the category name from the CSV
                $category_name = $data[0];

                // Check if the category already exists
$existing_category = get_term_by('name', $category_name, 'product_cat');

                if (!$existing_category) {
                    // Create the category if it does not exist
                    $category_id = wp_insert_term($category_name, 'product_cat');
                    if (!is_wp_error($category_id)) {
echo "Category '$category_name' created successfully.<br>";
                    } else {
                        // Error creating category
                        echo "Error creating category '$category_name': " . $category_id->get_error_message() . "<br>";
                    }
                } else {
// Category already exists
                    echo "The category '$category_name' already exists.<br>";
                }
            }
        } else {
            echo "Could not read lines from CSV file.";
        }
    } else {
        echo "The CSV file does not exist in the specified path.";
    }
}
// Call function to check existing categories
if (isset($_GET['eti']) && $_GET['eti'] == '1') {
    import_categories_from_csv();
}
1

There are 1 best solutions below

1
Tech Old Hand On

Before You Start

  • Ensure that WooCommerce is installed and activated on your WordPress site. Prepare your product data.
  • WooCommerce supports CSV file imports. Your CSV file should include product details such as name, description, price, categories, etc.

Step-by-Step Guide to Import Products with Categories

  1. Prepare Your CSV File
  • Your CSV file must have columns for all the product information, including product categories.

  • For categories, you can assign multiple categories to a product by separating them with a comma. If you're using hierarchical categories (subcategories), you can specify them using > to denote levels. For example, Clothing > Men > Shirts.

  • Make sure to match the column headers to the fields WooCommerce expects. You can find a sample CSV file and a list of all supported columns in the WooCommerce documentation.

  1. Access the Importer
  • In your WordPress dashboard, go to Products > All Products.

  • Above the product list, there's an Import button. Click it to start the import process.

  1. Upload Your CSV File
  • Click Choose file and select the CSV file from your computer. After selecting your file, click Continue.

  • WooCommerce will attempt to auto-match the column names in your CSV to product fields. Review these mappings to ensure they are correct. If WooCommerce doesn't automatically match a column correctly, you can manually adjust it using the dropdown menus.

  1. Run the Importer
  • Once you've mapped all columns correctly, click Run the importer.

  • WooCommerce will start importing products from your CSV file. This process might take some time, depending on the number of products.

  • When the import is complete, you'll see a success message.

  1. Tips for a Smooth Import
  • Test with a few products first: Before importing your entire catalog, try importing a small number of products to ensure everything works as expected.

  • Check your categories: Make sure that the categories in your CSV file match the categories in WooCommerce. If a category doesn't exist, WooCommerce should automatically create it, but it's good practice to have your category structure set up in advance.

  • Backup your data: Always backup your website before performing bulk operations, including product imports. This ensures you can restore your site to its previous state if anything goes wrong.


This method should cover most needs for importing products with categories. If you have more complex requirements, such as importing custom fields or handling very large datasets, you might explore plugin solutions like WP All Import or writing custom scripts.