Импортируйте товары в WooCommerce с категориями.Php

Кемеровские программисты php общаются здесь
Ответить
Гость
 Импортируйте товары в WooCommerce с категориями.

Сообщение Гость »


Я уже несколько недель пытаюсь импортировать продукты либо из CSV, либо из XML. Я могу импортировать такие данные, как изображение цены на название, но не могу импортировать категории. ни отдельно, ни вместе с одной и той же функцией

Код: Выделить всё

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


Источник: https://stackoverflow.com/questions/781 ... categories
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Php»