Created
November 25, 2023 07:59
-
-
Save dan-zakirov/f27a398a4e25a48bcf66916306a442a7 to your computer and use it in GitHub Desktop.
ЮНИКА - WP ALL IMPORT - cохранение атрибутов, запись категорий из другого узла xml, чистка из описания бяки
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Обработка товара при выполнении WP All Import. | |
* | |
* @param int $post_id Идентификатор поста. | |
* @param object $xml_node Узел XML. | |
* @param bool $is_update Определяет, обновляется ли пост. | |
*/ | |
function air_saved_post($post_id, $xml_node, $is_update) { | |
$import_id = wp_all_import_get_import_id(); | |
if ('1' === $import_id) { | |
$record = json_decode(json_encode((array)$xml_node), true); | |
// 1. Сохранение атрибутов | |
$product_attributes = []; | |
foreach ($xml_node->param as $param) { | |
$attribute_name = html_entity_decode((string)$param['name'], ENT_QUOTES, 'UTF-8'); | |
$attribute_value = html_entity_decode((string)$param, ENT_QUOTES, 'UTF-8'); | |
if (stripos($attribute_value, 'youtube') !== false) { | |
continue; | |
} | |
$product_attributes[] = array( | |
'name' => $attribute_name, | |
'value' => $attribute_value, | |
'is_visible' => 1, | |
'is_variation' => 0, | |
'is_taxonomy' => 0, | |
); | |
} | |
// Обновляем Атрибуты | |
add_post_meta($post_id, '_product_attributes', $product_attributes); | |
// 2. Добавление категорий к товарам | |
$cache_key = 'imported_files_' . $import_id; | |
$imported_files = wp_cache_get($cache_key); | |
if (false === $imported_files) { | |
global $wpdb; | |
$file_info = $wpdb->get_row($wpdb->prepare("SELECT path FROM {$wpdb->prefix}pmxi_files WHERE import_id = %d", $import_id)); | |
if ($file_info) { | |
$upload_dir = wp_get_upload_dir(); | |
$path = trailingslashit($upload_dir['basedir']) . ltrim($file_info->path, '/'); | |
wp_cache_set($cache_key, $file_info, '', 3600); | |
} else { | |
// error_log("No file info found for import ID: " . $import_id); | |
return; | |
} | |
} else { | |
$upload_dir = wp_get_upload_dir(); | |
$path = trailingslashit($upload_dir['basedir']) . ltrim($imported_files->path, '/'); | |
} | |
// Получаем ID категории из импорта | |
$category_id = isset($record['categoryId']) ? intval($record['categoryId']) : 0; | |
if ($category_id > 0) { | |
$xml_data = simplexml_load_file($path); | |
// Ищем категорию по ID | |
$result = []; | |
foreach ($xml_data->shop->categories->category as $category) { | |
if ((string)$category['id'] === (string)$category_id){ | |
// Нашли категорию по ID | |
$result[] = (string)$category; | |
// Проверяем, есть ли у нее родительская категория | |
if (isset($category['parentId'])) { | |
$parentCategoryId = (string)$category['parentId']; | |
// Рекурсивно ищем родителя | |
foreach ($xml_data->shop->categories->category as $parentCategory) { | |
if ((string)$parentCategory['id'] === $parentCategoryId) { | |
// Нашли родительскую категорию | |
$result[] = (string)$parentCategory; | |
// Проверяем, есть ли у нее родительская категория и так далее... | |
if (isset($parentCategory['parentId'])) { | |
$grandParentCategoryId = (string)$parentCategory['parentId']; | |
foreach ($xml_data->shop->categories->category as $grandParentCategory) { | |
if ((string)$grandParentCategory['id'] === $grandParentCategoryId) { | |
// Нашли родителя родителя | |
$result[] = (string)$grandParentCategory; | |
// Можем продолжать этот блок для более глубоких уровней, если необходимо | |
break; | |
} | |
} | |
} | |
break; | |
} | |
} | |
} | |
break; | |
} | |
} | |
$parent_category_id = 1; // ID родительской категории | |
// Перебираем категории в обратном порядке (с конца массива) | |
foreach (array_reverse($result) as $category_name) { | |
// Проверяем, существует ли текущая категория | |
$category = get_term_by('name', $category_name, 'product_cat'); | |
if (!$category) { | |
// Категории нет, создаем новую | |
$category_args = array( | |
'cat_name' => $category_name, | |
'taxonomy' => 'product_cat', | |
'description' => '', | |
'category_parent' => $parent_category_id, | |
'slug' => sanitize_title($category_name), | |
); | |
$category_id = wp_insert_category($category_args); | |
// Привязываем категорию к товару | |
wp_set_object_terms($post_id, $category_id, 'product_cat', true); | |
// Обновляем переменную с ID родительской категории | |
$parent_category_id = $category_id; | |
} else { | |
// Категория уже существует, просто привязываем к товару | |
wp_set_object_terms($post_id, $category->term_id, 'product_cat', true); | |
// Обновляем переменную с ID родительской категории | |
$parent_category_id = $category->term_id; | |
} | |
} | |
} | |
// 3. Фильтрация описания | |
$description = isset($record['description']) ? $record['description'] : ''; | |
// Ликвидация "Описание:" | |
$description = str_replace('Описание:', '', $description); | |
// Замена "Особенности:" | |
$description = str_replace('Особенности:', '<h3>Особенности:</h3>', $description); | |
// Замена "Комплектация:" | |
$description = str_replace('Комплектация:', '<h3>Комплектация:</h3>', $description); | |
// Удаление символов "#" | |
$description = str_replace('#', '', $description); | |
// Обновление описания | |
wp_update_post(array('ID' => $post_id, 'post_content' => $description)); | |
} | |
} | |
// Добавление хука | |
add_action('pmxi_saved_post', 'air_saved_post', 10, 3); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ловите миллиард комментариев как вы и хотели))
https://kedrweld.ru/bitrix/catalog_export/kedrweld-yml.xml по данному файлу работает