WC_API_Products::bulk()publicWC 2.4.0

Bulk update or insert products Accepts an array with products in the formats supported by WC_API_Products->create_product() and WC_API_Products->edit_product()

Метод класса: WC_API_Products{}

Возвращает

Массив|WP_Error.

Использование

$WC_API_Products = new WC_API_Products();
$WC_API_Products->bulk( $data );
$data(массив) (обязательный)
-

Список изменений

С версии 2.4.0 Введена.

Код WC_API_Products::bulk() WC 8.7.0

public function bulk( $data ) {

	try {
		if ( ! isset( $data['products'] ) ) {
			throw new WC_API_Exception( 'woocommerce_api_missing_products_data', sprintf( __( 'No %1$s data specified to create/edit %1$s', 'woocommerce' ), 'products' ), 400 );
		}

		$data  = $data['products'];
		$limit = apply_filters( 'woocommerce_api_bulk_limit', 100, 'products' );

		// Limit bulk operation
		if ( count( $data ) > $limit ) {
			throw new WC_API_Exception( 'woocommerce_api_products_request_entity_too_large', sprintf( __( 'Unable to accept more than %s items for this request.', 'woocommerce' ), $limit ), 413 );
		}

		$products = array();

		foreach ( $data as $_product ) {
			$product_id  = 0;
			$product_sku = '';

			// Try to get the product ID
			if ( isset( $_product['id'] ) ) {
				$product_id = intval( $_product['id'] );
			}

			if ( ! $product_id && isset( $_product['sku'] ) ) {
				$product_sku = wc_clean( $_product['sku'] );
				$product_id  = wc_get_product_id_by_sku( $product_sku );
			}

			if ( $product_id ) {

				// Product exists / edit product
				$edit = $this->edit_product( $product_id, array( 'product' => $_product ) );

				if ( is_wp_error( $edit ) ) {
					$products[] = array(
						'id'    => $product_id,
						'sku'   => $product_sku,
						'error' => array( 'code' => $edit->get_error_code(), 'message' => $edit->get_error_message() ),
					);
				} else {
					$products[] = $edit['product'];
				}
			} else {

				// Product don't exists / create product
				$new = $this->create_product( array( 'product' => $_product ) );

				if ( is_wp_error( $new ) ) {
					$products[] = array(
						'id'    => $product_id,
						'sku'   => $product_sku,
						'error' => array( 'code' => $new->get_error_code(), 'message' => $new->get_error_message() ),
					);
				} else {
					$products[] = $new['product'];
				}
			}
		}

		return array( 'products' => apply_filters( 'woocommerce_api_products_bulk_response', $products, $this ) );
	} catch ( WC_API_Exception $e ) {
		return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
	}
}