Product_Builder::build_images( int $parent_id )

Summary

No summary available.

Parameters

$parent_id

(int) (Required) The post that will be set as the attachment parent


Return

(array)


Source

File: src/BigCommerce/Import/Importers/Products/Product_Builder.php

	public function build_images( $parent_id ) {
		/** @var \wpdb $wpdb */
		global $wpdb;

		$response = [
			'thumbnail' => 0,
			'gallery'   => [],
			'variants'  => [],
		];

		/**
		 * Filters whether to import product images or not.
		 *
		 * @param bool $import_images True or false.
		 */
		if ( ! apply_filters( 'bigcommerce/import/product/import_images', true ) ) {
			return $response;
		}

		$images = $this->product[ 'images' ];
		usort( $images, function ( $a, $b ) {
			if ( $a[ 'sort_order' ] == $b[ 'sort_order' ] ) {
				return 0;
			}

			return ( $a[ 'sort_order' ] < $b[ 'sort_order' ] ) ? - 1 : 1;
		} );
		foreach ( $images as $image ) {
			/** @var ProductImage $image */

			// find an existing image
			$existing = get_posts( [
				'post_type'      => 'attachment',
				'meta_query'     => [
					[
						'key'     => 'bigcommerce_id',
						'value'   => $image[ 'id' ],
						'compare' => '=',
					],
				],
				'fields'         => 'ids',
				'posts_per_page' => 1,
			] );
			if ( ! empty( $existing ) ) {
				$post_id = reset( $existing );
			} else {
				$importer = new Image_Importer( $image[ 'url_zoom' ], $parent_id );
				$post_id  = $importer->import();
			}
			if ( ! empty( $post_id ) ) {
				update_post_meta( $post_id, 'bigcommerce_id', $image[ 'id' ] );
				foreach ( [ 'url_zoom', 'url_standard', 'url_thumbnail', 'url_tiny' ] as $key ) {
					$derivative_url = $image[ $key ];
					if ( $derivative_url ) {
						update_post_meta( $post_id, $key, $derivative_url );
					}
				}
				if ( ! empty( $image['description'] ) ) {
					update_post_meta( $post_id, '_wp_attachment_image_alt', $image['description'] );
				}
				$response[ 'gallery' ][] = $post_id;
				if ( $image[ 'is_thumbnail' ] ) {
					$response[ 'thumbnail' ] = $post_id;
				}
			}
		}

		$variants = $this->product->getVariants();
		foreach ( $variants as $var ) {
			$image_url = $var->getImageUrl();
			if ( $image_url ) {
				$existing = $wpdb->get_var( $wpdb->prepare(
					"SELECT p.ID FROM {$wpdb->posts} p
					 INNER JOIN {$wpdb->postmeta} m ON p.ID=m.post_id
					 WHERE p.post_type='attachment'
					   AND m.meta_key IN ( 'bigcommerce_source_url', 'url_zoom', 'url_standard', 'url_thumbnail', 'url_tiny' )
					   AND m.meta_value=%s ORDER BY p.ID ASC LIMIT 1",
					$image_url
				) );
				if ( ! empty( $existing ) ) {
					$post_id = (int) $existing;
				} else {
					$importer = new Image_Importer( $image_url, $parent_id );
					$post_id  = $importer->import();
				}
				if ( ! empty( $post_id ) ) {
					$response['variants'][ $var->getId() ] = $post_id;
				}
			}
		}

		return $response;
	}


User Contributed Notes

You must log in before being able to contribute a note or feedback.