[ranking_mikup]
function ure_run_universal_import($url, $limit) { $response = wp_remote_get($url, ['timeout' => 120, 'sslverify' => false, 'user-agent' => 'Mozilla/5.0']); if (is_wp_error($response)) return $response->get_error_message(); $body = preg_replace('/^[\x00-\x1F\x7F\xEF\xBB\xBF]+/', '', trim(wp_remote_retrieve_body($response))); $xml = @simplexml_load_string($body, 'SimpleXMLElement', LIBXML_NOCDATA); if (!$xml) return "Błąd struktury XML."; $items = $xml->xpath('//o') ?: $xml->xpath('//item'); if (!$items) return "Nie znaleziono produktów."; $stats = ['added' => 0, 'skipped' => 0]; foreach ($items as $item) { if ($limit > 0 && $stats['added'] >= $limit) break; $title = (string)($item->name ?: $item->title); // Pobieranie kategorii z atrybutu 'cat' (Ceneo) lub pola 'product_type' (Google) $cat_path = ''; if (isset($item['cat'])) { $cat_path = (string)$item['cat']; } elseif (isset($item->children('g', true)->product_type)) { $cat_path = (string)$item->children('g', true)->product_type; } if (get_page_by_path(sanitize_title($title), OBJECT, 'ur_product')) { $stats['skipped']++; continue; } $post_id = wp_insert_post([ 'post_type' => 'ur_product', 'post_title' => $title, 'post_content' => (string)($item->desc ?: $item->description), 'post_status' => 'publish' ]); if ($post_id) { // PRZYPISANIE KATEGORII if (!empty($cat_path)) { ure_assign_category_from_xml($post_id, $cat_path); } // Meta dane update_post_meta($post_id, '_product_url', esc_url_raw((string)($item['url'] ?: $item->link))); update_post_meta($post_id, '_price', sanitize_text_field((string)($item['price'] ?: $item->children('g', true)->price))); $stats['added']++; } } return $stats; } function ure_assign_category_from_xml($post_id, $cat_path) { // Rozbijamy ścieżkę (np. "Meble/Sofy") na poszczególne nazwy $categories = explode('/', $cat_path); $parent_id = 0; $term_ids = []; foreach ($categories as $cat_name) { $cat_name = trim($cat_name); if (empty($cat_name)) continue; // Sprawdzamy, czy kategoria istnieje na danym poziomie $term = term_exists($cat_name, 'category', $parent_id); if (!$term) { // Jeśli nie istnieje, tworzymy ją $term = wp_insert_term($cat_name, 'category', ['parent' => $parent_id]); } if (!is_wp_error($term)) { $term_id = is_array($term) ? $term['term_id'] : $term; $term_ids[] = (int)$term_id; $parent_id = $term_id; // Ustawiamy jako rodzica dla następnej podkategorii } } // Przypisujemy produkt do wszystkich znalezionych/stworzonych kategorii if (!empty($term_ids)) { wp_set_post_categories($post_id, $term_ids); } }
[ranking_mikup]