Skip to content

Instantly share code, notes, and snippets.

@lukeholder
Last active January 10, 2018 09:58
Show Gist options
  • Save lukeholder/bbff8caef82078fc76e4 to your computer and use it in GitHub Desktop.
Save lukeholder/bbff8caef82078fc76e4 to your computer and use it in GitHub Desktop.
Basic example to import Products and their variants into Craft Commerce
<?php
namespace Craft;
// This file could be placed into your public_html folder and visited to import a cheese product.
$craft = require '../craft/app/bootstrap.php';
$craft->plugins->loadPlugins();
$newProduct = new Commerce_ProductModel();
$newProduct->typeId = 1; // Replace with product type ID;
$newProduct->enabled = true;
$newProduct->promotable = true;
$newProduct->freeShipping = 0;
$newProduct->postDate = new DateTime();
$newProduct->taxCategoryId = craft()->commerce_taxCategories->getDefaultTaxCategory()->id;
$newProduct->getContent()->title = "Cheese";
$newProduct->slug = StringHelper::toKebabCase("Cheese");
// Product custom fields
// $product->setContentFromPost(array('customFieldName'=>'value'));
$variant = new Commerce_VariantModel();
$variant->setProduct($newProduct);
$variant->sortOrder = 1;
$variant->getContent()->title = "Cheese";
$variant->sku = "10101";
$variant->price = "10";
$variant->unlimitedStock = true;
$newProduct->setVariants([$variant]);
if(craft()->commerce_products->saveProduct($newProduct)){
echo "done";
}else{
$errors = $newProduct->getAllErrors();
foreach ($errors as $error) {
echo $error;
echo "<br>";
}
foreach ($newProduct->getVariants() as $variant) {
$errors = $variant->getAllErrors();
foreach ($errors as $error) {
echo $error;
echo "<br>";
}
}
};
$craft->end();
@pixeldeluxe
Copy link

@lukeholder Tnx for the fix.
How should I use this script to import 800 products? And how do I set custom fields. The above row isn't working when I unquote it. Tnx in advance.

@lukeclifton
Copy link

I may be wrong but i think line 32 is not needed here as line 25 is already setting the product onto the variant.
If you look into the $product->setVariants() method its just calling $variant->setProduct() internally.

@Wiejeben
Copy link

Line 17 doesn't work anymore. Replacing it with $newProduct->taxCategoryId = craft()->commerce_taxCategories->getDefaultTaxCategory()->id; fixes it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment