Automattic\WooCommerce\Blocks\Images

Pexels::get_images()publicWC 1.0

Returns the list of images for the given search criteria.

Method of the class: Pexels{}

No Hooks.

Return

Array|\WP_Error. Array of images, or WP_Error if the request failed.

Usage

$Pexels = new Pexels();
$Pexels->get_images( $ai_connection, $token, $business_description );
$ai_connection(Connection) (required)
The AI connection.
$token(string) (required)
The JWT token.
$business_description(string) (required)
The business description.

Pexels::get_images() code WC 9.4.2

public function get_images( $ai_connection, $token, $business_description ) {
	$business_description = ContentProcessor::summarize_business_description( $business_description, $ai_connection, $token );

	if ( str_word_count( $business_description ) === 1 ) {
		$search_term = $business_description;
	} else {
		$search_term = $this->define_search_term( $ai_connection, $token, $business_description );
	}

	if ( is_wp_error( $search_term ) ) {
		return $search_term;
	}

	$required_images = $this->total_number_required_images();

	if ( is_wp_error( $required_images ) ) {
		return $required_images;
	}

	$returned_images = $this->request( $search_term );

	if ( is_wp_error( $returned_images ) ) {
		return $returned_images;
	}

	$refined_images = $this->refine_returned_images_results( $ai_connection, $token, $business_description, $returned_images );

	if ( is_wp_error( $refined_images ) ) {
		return $returned_images;
	}

	$refined_images_count = count( $refined_images );

	$i      = 0;
	$errors = array();
	while ( $refined_images_count < $required_images && $i < 5 ) {
		$i ++;
		$search_term = $this->define_search_term( $ai_connection, $token, $business_description );

		if ( is_wp_error( $search_term ) ) {
			$errors[] = $search_term;
			continue;
		}

		$images_to_add = $this->request( $search_term );

		if ( is_wp_error( $images_to_add ) ) {
			$errors[] = $images_to_add;
			continue;
		}

		$images_to_add = $this->refine_returned_images_results( $ai_connection, $token, $business_description, $images_to_add );

		if ( is_wp_error( $images_to_add ) ) {
			$errors[] = $images_to_add;
			continue;
		}

		$refined_images = array_merge( $refined_images, $images_to_add );
	}

	if ( $refined_images_count < $required_images && ! empty( $errors ) ) {
		return new \WP_Error( 'ai_service_unavailable', __( 'AI Service is unavailable, try again later.', 'woocommerce' ), $errors );
	}

	if ( empty( $refined_images ) ) {
		return new \WP_Error( 'woocommerce_no_images_found', __( 'No images found.', 'woocommerce' ) );
	}

	return array(
		'images'      => $refined_images,
		'search_term' => $search_term,
	);
}