Automattic\WooCommerce\Internal\CLI\Migrator\Core

WooCommerceProductImporter::find_existing_productprivateWC 1.0

Find existing product by various identifiers.

Method of the class: WooCommerceProductImporter{}

No Hooks.

Returns

Int|null. Existing product ID or null if not found.

Usage

// private - for code of main (parent) class only
$result = $this->find_existing_product( $product_data ): ?int;
$product_data(array) (required)
Mapped product data.

WooCommerceProductImporter::find_existing_product() code WC 10.7.0

private function find_existing_product( array $product_data ): ?int {
	if ( ! empty( $product_data['original_product_id'] ) ) {
		$existing_posts = get_posts(
			array(
				'post_type'   => 'product',
				'post_status' => 'any', // Find regardless of status.
				'meta_key'    => '_original_product_id', // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
				'meta_value'  => $product_data['original_product_id'], // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value
				'fields'      => 'ids',
				'numberposts' => 1,
			)
		);

		if ( ! empty( $existing_posts ) ) {
			return (int) $existing_posts[0];
		}
	}

	if ( ! empty( $product_data['sku'] ) ) {
		$product_id = wc_get_product_id_by_sku( $product_data['sku'] );
		if ( $product_id ) {
			return $product_id;
		}
	}

	if ( ! empty( $product_data['slug'] ) ) {
		$post = get_page_by_path( $product_data['slug'], OBJECT, 'product' );
		if ( $post ) {
			return $post->ID;
		}
	}

	return null;
}