Skip to content

Instantly share code, notes, and snippets.

@trey8611
Last active April 11, 2023 09:38
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save trey8611/b0ab4e02b118fbfe013566c0b62a2944 to your computer and use it in GitHub Desktop.
Save trey8611/b0ab4e02b118fbfe013566c0b62a2944 to your computer and use it in GitHub Desktop.
WP All Import & WooCommerce Add-On - Import XML files using YML format ( Yandex ) | custom function

Importing XML files using YML Format

How to import the categories properly

Since the categories are listed separately, and are based on IDs, you will need to import them first in a "Taxonomies" import:

Taxonomies Import

On step 2 of the import, choose the "category" element:

Category Element

On step 3 (the import template), you'll need to save the "id" attribute inside a term meta field named "_category_id":

Term Meta

And, use an IF statement along with a custom PHP function (see documentation) in the "Parent Term" field:

[IF({./@parentId[.!=""]})][my_get_category({./@parentId})][ELSE][ENDIF]

Function

Here's the code for the function:

function my_get_category( $id ) {
	$term = get_terms( array(
			'taxonomy' => 'product_cat',
			'hide_empty' => false,
			'meta_query' => array(
				array(
					'key'       => '_category_id',
					'value'     => $id,
					'compare'   => '='
				)
			)
		)
	);
	if ( ! empty( $term ) ) {
		return $term[0]->slug;
	}		
}

After you've imported your taxonomies with these settings, you'll be able to retrieve the category names/slugs using the same function when importing your Products:

[my_get_category({categoryId[1]})]

Category Product Import

How to import the Attributes when importing your Products

There are a couple of things to keep in mind when importing the attributes for your products:

  1. The "param" elements can vary in position on each import record, and they use Cyrillic symbols, so you'll need to query them using the instructions here: Query Cyrillic Attribute Values.
  2. You'll need to manually map each attribute in the import template. It's not possible to dynamically import a varying amount of attributes per-record.
@stanislavna
Copy link

Свяжитесь со мной пожалуйста Len55555@yandex.ru

@2PyKu
Copy link

2PyKu commented Dec 2, 2020

Здравствуйте.
Не знаю, что я делаю неправильно, но часть категорий дублируется со слагом cаtegory-name-2 и именем cаtegory-name, вместо Категори Наме. Подробности на скриншоте http://joxi.ru/GrqndjVcGLoYlm. Возможно, это из-за одинаковых названий подкатегорий в некоторых категориях. Я использую плагин транслитерации Кириллицы.
WP All Import может сопоставлять товары с категориями по слагу, поэтому раньше я импортировал сначала категории из YML файлов, указывая в качестве slug'a ID категории:
<category id="148" parentId="140">Все товары/Спорт и отдых/Скейтбординг/Скейтборды и лонгборды</category>
а потом при импорте товаров тоже указывал category id. Импортировалось правильно, но урлы категорий были в виде site.ru/product-category/148/140, что не очень хорошо, не ЧПУ. Шаблон импорта: https://cloud.mail.ru/public/SXiH/2Ya1CuvTf
Поэтому идея такая: что если импортировать категории и товары как я описал выше, получив site.ru/product-category/148/140, а затем добавить в functions.php код редиректа через хук template_redirect, использовав для создания хука строчки из файла YML с категориями <category id="148" parentId="140">Все товары/Спорт и отдых/Скейтбординг/Скейтборды и лонгборды</category>, добавив поиском-заменой нужный код до и после или использовав другой метод замены слага по имени категории.
Напишите мне Ваше мнение, если Вам интересен этот вопрос 2816175@mail.ru
Спасибо

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment