WC_Admin_Importers::post_importer_compatibility()
When running the WP XML importer, ensure attributes exist.
Description Description
WordPress import should work – however, it fails to import custom product attribute taxonomies. This code grabs the file before it is imported and ensures the taxonomies are created.
Source Source
File: includes/admin/class-wc-admin-importers.php
public function post_importer_compatibility() {
global $wpdb;
if ( empty( $_POST['import_id'] ) || ! class_exists( 'WXR_Parser' ) ) { // PHPCS: input var ok, CSRF ok.
return;
}
$id = absint( $_POST['import_id'] ); // PHPCS: input var ok.
$file = get_attached_file( $id );
$parser = new WXR_Parser();
$import_data = $parser->parse( $file );
if ( isset( $import_data['posts'] ) && ! empty( $import_data['posts'] ) ) {
foreach ( $import_data['posts'] as $post ) {
if ( 'product' === $post['post_type'] && ! empty( $post['terms'] ) ) {
foreach ( $post['terms'] as $term ) {
if ( strstr( $term['domain'], 'pa_' ) ) {
if ( ! taxonomy_exists( $term['domain'] ) ) {
$attribute_name = wc_attribute_taxonomy_slug( $term['domain'] );
// Create the taxonomy.
if ( ! in_array( $attribute_name, wc_get_attribute_taxonomies(), true ) ) {
wc_create_attribute(
array(
'name' => $attribute_name,
'slug' => $attribute_name,
'type' => 'select',
'order_by' => 'menu_order',
'has_archives' => false,
)
);
}
// Register the taxonomy now so that the import works!
register_taxonomy(
$term['domain'],
apply_filters( 'woocommerce_taxonomy_objects_' . $term['domain'], array( 'product' ) ),
apply_filters(
'woocommerce_taxonomy_args_' . $term['domain'],
array(
'hierarchical' => true,
'show_ui' => false,
'query_var' => true,
'rewrite' => false,
)
)
);
}
}
}
}
}
}
}