Skip to content

Instantly share code, notes, and snippets.

@artikus11
Last active January 12, 2022 12:00
Show Gist options
  • Save artikus11/b90290147f3ac5df9a2fc6e1bd3b1717 to your computer and use it in GitHub Desktop.
Save artikus11/b90290147f3ac5df9a2fc6e1bd3b1717 to your computer and use it in GitHub Desktop.
Создание атрибутов из строки при импорте товаров
/**
* Создание атрибутов из строки при импорте товаров
*
* @param int $post_id ID созданного товара
* @param object $xml_node Объект узла
*
* @author Artem Abramovich
* @verphp 7.4
*/
function art_adding_attributes( $post_id, $xml_node ) {
// Ограничиваем работу сниппета нужным импортом
$import_id = ( $_GET['id'] ?? ( isset( $_GET['import_id'] ) ? $_GET['import_id'] : 'new' ) );
if ( '47' !== $import_id ) {
return;
}
$attributes_from_string = [];
$attributes = [];
// Парсим строку с атрибутами и получаем массив формата [Тип двигателя => бензиновый]
if ( $xml_node->attr ) {
$attr = str_replace( [ '<table>', '</table>', '<tr>', '</tr>' ], '', $xml_node->attr );
$attr = explode( '<td>', $attr );
unset( $attr[0] );
$attr = array_map( 'sanitize_text_field', $attr );
$chunks = array_chunk( $attr, 2 );
$attributes_from_string = array_combine( array_column( $chunks, 0 ), array_column( $chunks, 1 ) );
}
// Проверяем, что нужный массив существует
if ( ! empty( $attributes_from_string ) ) {
foreach ( $attributes_from_string as $name => $value ) {
// Проверяем на наличие ключа и значения
if ( empty( $name ) || empty( $value ) ) {
continue;
}
// Превращаем занчения в массив
if ( ! is_array( $value ) ) {
$value = array_map( 'trim', explode( ',', $value ) );
}
$attribute_id = 0;
$slug = wc_sanitize_taxonomy_name( $name );
$taxonomy_name = wc_attribute_taxonomy_name( $name );
$attribute_taxonomies = wc_get_attribute_taxonomies();
// Создаем таксономию глобального атрибута, если ее еще нет
if ( ! taxonomy_exists( $taxonomy_name ) ) {
$attribute_name = wc_attribute_taxonomy_slug( $name );
// Create the taxonomy.
if ( ! in_array( $attribute_name, $attribute_taxonomies, true ) ) {
$attribute_id = wc_create_attribute(
[
'name' => $name,
'slug' => $attribute_name,
'type' => 'select',
'order_by' => 'menu_order',
'has_archives' => false,
]
);
}
register_taxonomy(
$taxonomy_name,
apply_filters( 'woocommerce_taxonomy_objects_' . $taxonomy_name, [ 'product' ] ),
apply_filters(
'woocommerce_taxonomy_args_' . $taxonomy_name,
[
'hierarchical' => true,
'show_ui' => false,
'query_var' => true,
'rewrite' => false,
]
)
);
} else {
// Иначе, просто присваиваем нужное значение в нужную таксу
$taxonomies = wp_list_pluck( $attribute_taxonomies, 'attribute_id', 'attribute_name' );
if ( ! isset( $taxonomies[ $slug ] ) ) {
continue;
}
$attribute_id = (int) $taxonomies[ $slug ];
}
// Создаем атрибуты
$attribute = new WC_Product_Attribute();
$attribute->set_id( $attribute_id );
$attribute->set_name( $taxonomy_name );
$attribute->set_options( $value );
$attribute->set_visible( true );
$attribute->set_variation( false );
$attributes[] = $attribute;
}
// И добавляем созданные атрибуты в товар
$product = wc_get_product( $post_id );
$product->set_attributes( $attributes );
$product->save();
}
}
add_action( 'pmxi_saved_post', 'art_adding_attributes', 10, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment