From 90f0a835b10bdd0ba701ae95a76e92ee55a0b09b Mon Sep 17 00:00:00 2001 From: Mike Jolley Date: Tue, 8 Aug 2017 15:00:03 +0100 Subject: [PATCH] Fix filename image handling --- includes/import/abstract-wc-product-importer.php | 14 ++++++++------ includes/import/class-wc-product-csv-importer.php | 14 ++++++++++++-- 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/includes/import/abstract-wc-product-importer.php b/includes/import/abstract-wc-product-importer.php index e7ce0cfb359..d6404a8a370 100644 --- a/includes/import/abstract-wc-product-importer.php +++ b/includes/import/abstract-wc-product-importer.php @@ -504,8 +504,8 @@ abstract class WC_Product_Importer implements WC_Importer_Interface { $base_url = $upload_dir['baseurl'] . '/'; // Check first if attachment is on WordPress uploads directory. - if ( false !== strpos( $url, $base_url ) ) { - // Search for yyyy/mm/slug.extension + if ( false === strpos( $url, $base_url ) ) { + // Search for yyyy/mm/slug.extension. $file = str_replace( $base_url, '', $url ); $args = array( 'post_type' => 'attachment', @@ -515,11 +515,10 @@ abstract class WC_Product_Importer implements WC_Importer_Interface { array( 'value' => $file, 'compare' => 'LIKE', - 'key' => '_wp_attachment_metadata', + 'key' => '_wp_attached_file', ), ), ); - if ( $ids = get_posts( $args ) ) { $id = current( $ids ); } @@ -535,14 +534,13 @@ abstract class WC_Product_Importer implements WC_Importer_Interface { ), ), ); - if ( $ids = get_posts( $args ) ) { $id = current( $ids ); } } // Upload if attachment does not exists. - if ( ! $id ) { + if ( ! $id && stristr( $url, '://' ) ) { $upload = wc_rest_upload_image_from_url( $url ); if ( is_wp_error( $upload ) ) { @@ -559,6 +557,10 @@ abstract class WC_Product_Importer implements WC_Importer_Interface { update_post_meta( $id, '_wc_attachment_source', $url ); } + if ( ! $id ) { + throw new Exception( sprintf( __( 'Unable to use image "%s".', 'woocommerce' ), $url ), 400 ); + } + return $id; } diff --git a/includes/import/class-wc-product-csv-importer.php b/includes/import/class-wc-product-csv-importer.php index aa69148a32e..fbc32877495 100644 --- a/includes/import/class-wc-product-csv-importer.php +++ b/includes/import/class-wc-product-csv-importer.php @@ -377,7 +377,7 @@ class WC_Product_CSV_Importer extends WC_Product_Importer { } /** - * Parse images list from a CSV. + * Parse images list from a CSV. Images can be filenames or URLs. * * @param string $field Field value. * @return array @@ -387,7 +387,17 @@ class WC_Product_CSV_Importer extends WC_Product_Importer { return array(); } - return array_map( 'esc_url_raw', $this->explode_values( $field ) ); + $images = array(); + + foreach ( $this->explode_values( $field ) as $image ) { + if ( stristr( $image, '://' ) ) { + $images[] = esc_url_raw( $image ); + } else { + $images[] = sanitize_file_name( $image ); + } + } + + return $images; } /**