Merge pull request #7922 from Nils-Fredrik/master
Allow bulk updates / inserts of products according to #7915
This commit is contained in:
commit
abf1d90d9b
|
@ -75,10 +75,15 @@ class WC_API_Products extends WC_API_Resource {
|
||||||
$routes[ $this->base . '/sku/(?P<sku>\w+)' ] = array(
|
$routes[ $this->base . '/sku/(?P<sku>\w+)' ] = array(
|
||||||
array( array( $this, 'get_product_by_sku' ), WC_API_Server::READABLE ),
|
array( array( $this, 'get_product_by_sku' ), WC_API_Server::READABLE ),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
# POST /products/bulk
|
||||||
|
$routes[ $this->base . '/bulk' ] = array(
|
||||||
|
array( array( $this, 'bulk' ), WC_API_SERVER::CREATABLE | WC_API_Server::ACCEPT_DATA ),
|
||||||
|
);
|
||||||
|
|
||||||
return $routes;
|
return $routes;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get all products
|
* Get all products
|
||||||
*
|
*
|
||||||
|
@ -1957,4 +1962,38 @@ class WC_API_Products extends WC_API_Resource {
|
||||||
// Delete product
|
// Delete product
|
||||||
wp_delete_post( $product_id, true );
|
wp_delete_post( $product_id, true );
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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()
|
||||||
|
*
|
||||||
|
* @param array $products
|
||||||
|
* @throws Exception
|
||||||
|
*/
|
||||||
|
public function bulk( $data ) {
|
||||||
|
$products = array();
|
||||||
|
foreach ( $data as $_product ) {
|
||||||
|
try {
|
||||||
|
$existing = $this->get_product_by_sku( $_product['sku'] );
|
||||||
|
if(is_wp_error($existing) && $existing->get_error_code() === "woocommerce_api_invalid_product_sku") {
|
||||||
|
// SKU not found, go ahead and crate!
|
||||||
|
$result = $this->create_product($_product);
|
||||||
|
} else {
|
||||||
|
// Assume existing, update
|
||||||
|
$result = $this->edit_product( $existing['product']['id'], $_product );
|
||||||
|
}
|
||||||
|
if(is_wp_error($result)) {
|
||||||
|
// if it fails, add the error message to the return object. Do not! stop further execution.
|
||||||
|
$products[ $_product['sku'] ] = array( 'error' => array( 'code' => $result->get_error_code(), 'message' => $result->get_error_message() ) );
|
||||||
|
} else {
|
||||||
|
// If everything is well, add the updated or created product to the return array
|
||||||
|
$products[ $_product['sku'] ] = $result;
|
||||||
|
}
|
||||||
|
} catch(Exception $e) {
|
||||||
|
$products[ $_product['sku'] ] = array( 'error' => array( 'code' => $e->getCode(), 'message' => $e->getMessage() ) );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return array('products'=>$products);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue