Я уже несколько недель пытаюсь импортировать продукты либо из CSV, либо из XML. Я могу импортировать такие данные, как изображение цены на название, но не могу импортировать категории. ни отдельно, ни вместе с одной и той же функцией
идея состоит в том, чтобы автоматизировать ее с помощью ежедневного 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();
}
Я оставил попытки с комментариями, чтобы вы знали, чего я хотел достичь.
Я надеюсь знать, какие шаги следует предпринять, если мне придется разделить процесс на этапы или Я могу сделать это в той же функции
Я уже несколько недель пытаюсь импортировать продукты либо из CSV, либо из XML. Я могу импортировать такие данные, как изображение цены на название, но не могу импортировать категории. ни отдельно, ни вместе с одной и той же функцией идея состоит в том, чтобы автоматизировать ее с помощью ежедневного cronjob [code]function import_products_from_csv() { // Path of the CSV file on your server $local_file_path = WP_CONTENT_DIR . '/../products.csv';
// 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 (!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' );
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(); } [/code] Я оставил попытки с комментариями, чтобы вы знали, чего я хотел достичь. Я надеюсь знать, какие шаги следует предпринять, если мне придется разделить процесс на этапы или Я могу сделать это в той же функции