WPPostsImporter.php
88 lines
| 1 | <?php |
| 2 | |
| 3 | declare( strict_types=1 ); |
| 4 | |
| 5 | namespace Automattic\WooCommerce\Internal\Integrations; |
| 6 | |
| 7 | /** |
| 8 | * Class WPPostsImporter |
| 9 | * |
| 10 | * @since 10.1.0 |
| 11 | */ |
| 12 | class WPPostsImporter { |
| 13 | |
| 14 | /** |
| 15 | * Register the WP Posts importer. |
| 16 | * |
| 17 | * @return void |
| 18 | */ |
| 19 | public function register() { |
| 20 | add_action( 'wp_import_posts', array( $this, 'register_product_attribute_taxonomies' ), 100, 1 ); |
| 21 | } |
| 22 | |
| 23 | /** |
| 24 | * Register product attribute taxonomies when importing posts via the WXR importer. |
| 25 | * |
| 26 | * @since 10.1.0 |
| 27 | * |
| 28 | * @param array $posts The posts to process. |
| 29 | * @return array |
| 30 | */ |
| 31 | public function register_product_attribute_taxonomies( $posts ) { |
| 32 | if ( ! is_array( $posts ) || empty( $posts ) ) { |
| 33 | return $posts; |
| 34 | } |
| 35 | |
| 36 | foreach ( $posts as $post ) { |
| 37 | |
| 38 | if ( 'product' !== $post['post_type'] || empty( $post['terms'] ) ) { |
| 39 | continue; |
| 40 | } |
| 41 | |
| 42 | foreach ( $post['terms'] as $term ) { |
| 43 | if ( ! strstr( $term['domain'], 'pa_' ) ) { |
| 44 | continue; |
| 45 | } |
| 46 | |
| 47 | if ( taxonomy_exists( $term['domain'] ) ) { |
| 48 | continue; |
| 49 | } |
| 50 | |
| 51 | $attribute_name = wc_attribute_taxonomy_slug( $term['domain'] ); |
| 52 | |
| 53 | // Create the taxonomy. |
| 54 | if ( ! in_array( $attribute_name, wc_get_attribute_taxonomies(), true ) ) { |
| 55 | wc_create_attribute( |
| 56 | array( |
| 57 | 'name' => $attribute_name, |
| 58 | 'slug' => $attribute_name, |
| 59 | 'type' => 'select', |
| 60 | 'order_by' => 'menu_order', |
| 61 | 'has_archives' => false, |
| 62 | ) |
| 63 | ); |
| 64 | } |
| 65 | |
| 66 | // Register the taxonomy so that the import works. |
| 67 | register_taxonomy( |
| 68 | $term['domain'], |
| 69 | // phpcs:ignore |
| 70 | apply_filters( 'woocommerce_taxonomy_objects_' . $term['domain'], array( 'product' ) ), |
| 71 | // phpcs:ignore |
| 72 | apply_filters( |
| 73 | 'woocommerce_taxonomy_args_' . $term['domain'], |
| 74 | array( |
| 75 | 'hierarchical' => true, |
| 76 | 'show_ui' => false, |
| 77 | 'query_var' => true, |
| 78 | 'rewrite' => false, |
| 79 | ) |
| 80 | ) |
| 81 | ); |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | return $posts; |
| 86 | } |
| 87 | } |
| 88 |