Skip to content

Instantly share code, notes, and snippets.

@keithmancuso
Created June 17, 2016 22:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keithmancuso/450df42a0d245fd22c735bd40f2abfc4 to your computer and use it in GitHub Desktop.
Save keithmancuso/450df42a0d245fd22c735bd40f2abfc4 to your computer and use it in GitHub Desktop.
Move Craft Content Between Element Types
<?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();
$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = 'books';
$criteria->order = 'postDate desc';
$criteria->limit = 5;
foreach ($criteria as $entry)
{
// load product and varient
$newProduct = new Commerce_ProductModel();
$newProduct->typeId = 4; // Replace with product type ID;
$newProduct->enabled = true;
$newProduct->promotable = true;
$newProduct->freeShipping = 0;
$newProduct->postDate = $entry->postDate;
$newProduct->taxCategoryId = craft()->commerce_taxCategories->getDefaultTaxCategoryId();
$newProduct->getContent()->title = $entry->getContent()->title ;
$newProduct->slug = StringHelper::toKebabCase($entry->getContent()->title);
$newProduct->setContent($entry->getContent());
$variant = new Commerce_VariantModel();
$variant->setProduct($newProduct);
$variant->sortOrder = 1;
$variant->getContent()->title = $entry->getContent()->title;
$variant->sku = $entry->slug.'1';
$variant->price = "0";
$variant->unlimitedStock = true;
$newProduct->setVariants([$variant]);
if(craft()->commerce_products->saveProduct($newProduct)){
echo "done";
// get all the relations fields from entry and move over
$fields = $entry->fieldLayout->fields;
foreach ($fields as $fieldModel) {
$field = $fieldModel->getField();
if ($field->type == 'Assets' || $field->type == 'Entries' || $field->type == 'Categories') {
craft()->relations->saveRelations($field, $newProduct, $entry->{$field->handle}->ids());
} else if ( $field->type == 'Matrix') {
foreach ($entry->{$field->handle} as $block) {
$block->ownerId = $newProduct->id;
craft()->matrix->saveBlock($block);
}
}
}
} 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();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment