Copy and Paste Category in Magento - php

I want to copy my first category to a second category in Magento.
What should I do?
Thanks,
Wesley.

By code:
<?php
$category = Mage::getModel('catalog/category')
->load(123); // The ID of the category you want to copy.
$copy = clone $category;
$copy->setId(null) // Remove the ID.
->save();

If you want to do it in a programmatic way you can use the Magento API.
Use:
catalog_category.info - to read a category
catalog_category.create - to create a new one by copying data from existing.
Here are the docs for category API

I wouldn't clone the category object, but rather do something like this (using the Magento API - http://www.magentocommerce.com/wiki/doc/webservices-api/catalog_category ):
get the category which must be copied
$source_category = Mage::getModel('catalog/category')->load($id);
Create a new category using the API
$CategoryApi = new Mage_Catalog_Model_Category_Api();
$parent_id = /* Location for the new category */
$new_category_id = $CategoryApi->create(
$parent_id,
array(
/* Attributes to fill with source category values. */
)
);
Get the source category products and place them in the new category, again with the API.
$products = $CategoryApi->assignedProducts(source_category->getId());
foreach($products as $product)
{
$CategoryApi->assignProduct($product->getId())
}
Above must be done recursively for each subcategory.
Note: Using the API ensures your code will still work when you upgrade the Magento core.

All the replies here were not complete. I did a script that does the total Creating the new category, subcategories and assigning the products to them.
public function run()
{
$categoryId = 123;
// Change this if you want the copy to be under another category than the default
$baseCategoryId = 2;
$category = Mage::getModel('catalog/category')->load($categoryId);
$defaultCategory = Mage::getModel('catalog/category')->load($baseCategoryId);
$this->duplicate($category, $defaultCategory, 1);
}
private function duplicate($categoryToClone, $parentCategory, $level)
{
// This will clone the clild and assign it to the new parent
$newCategory = clone $categoryToClone;
$newCategory->setPath($parentCategory->getPath())
->setParentId($parentCategory->getId())
->setId(null);
// Optional, Only change the new with suffix with "new" for the first
if ($level == 1) {
$newCategory->setUrlKey($categoryToClone->getUrlKey() . '-new')
->setName($categoryToClone->getName() . '(new)');
}
// Assign all products from the cloned category to the new
$newCategory->setPostedProducts($categoryToClone->getProductsPosition());
$newCategory->save();
// Applies the changes to the subcategories infinite levels
$subcategories = $categoryToClone->getChildrenCategories();
if (count($subcategories) > 0) {
foreach ($subcategories as $subcategory) {
$this->duplicate($subcategory, $newCategory, ++$level);
}
}
}

You can't with the admin interface, you need. to create a script with the category api.

Sorry you cannot copy/paste Category directly in Magento Admin panel through the interface, which Catalog Products can offer with the help of "Duplicate" button.
I suppose you will need to write a script fetching the category details by first loading the Category model with the required Category ID.

This forum post contains instructions and code for importing your categories from a CSV file.
Good luck,
JD

I think you want to export products from a specific cat and import it to another one. if it's so use the steps bellow:
login to magento backend
navigate to System -> Import/Export
Create a new advanced profile for your cat
export it
now import it in the same fashion

Sometime we need to copy same products to another category.(Like we have two stores with same category or within same store need to copy the category products to somewhere else)
Adding product from back-end is very time consuming process you can do it by code.
You can create a file in your root directory copy-products.php with the following code to copy product:
<?php
require_once ( "app/Mage.php" );
umask(0);
// Initialize Magento
Mage::app();
$category = Mage::getModel('catalog/category');
$category->load('24'); // Category id you want to copy
$collection = $category->getProductCollection();
$collection->addAttributeToSelect('*');
foreach ($collection as $product) {
$product->getId();// Now get category ids and add a specific category to them and save?
$categories = $product->getCategoryIds();
$categories[] = 29; // Category id you want to add
$product->setCategoryIds($categories);
$product->save();
}
?>

Related

Magento - Get the associated product attributes of an item in the wishlist

In app/code/local/Mage/Catalog/Product/Type/Configurable/Price.php, I am trying to get the attribute values of an associated product within the wishlist. I've attempted several approaches but I can only seem to produce data for the parent product.
Latest attempt
$customer = Mage::getSingleton('customer/session')->getCustomer();
if($customer->getId()) {
$wishlist = Mage::getModel('wishlist/wishlist')->loadByCustomer($customer, true);
$wishListItemCollection = $wishlist->getItemCollection();
foreach ($wishListItemCollection as $wlitem) {
$wishitem = Mage::getModel('catalog/product')->setStoreId($wlitem->getStoreId())->load($wlitem->getProductId());
//echo $wishitem->getId() . '<br>';
if($product->getId() == $wishitem->getId()) { //if the current product id equals the wishlist product id
echo $wishitem->getSku()."</br>";
}
}
}
That only gets me the parent product's sku. What I ultimately want to get is the attribute value for 2 attributes that I added for configurable products (not super attributes) but it seems that $product in Price.php only has the parent product collection.
Other Attempts:
$item_s = Mage::getModel('wishlist/item')->loadWithOptions($product->getId(), 'simple_product')->getOptionsByCode();
$simple_product = $item_s['simple_product']->getData();
$simple_product_id = $simple_product['product_id'];
$sim_product = Mage::getModel('catalog/product')->load($simple_product_id);
print_r($sim_product);
This only resulted in an error on the page.
Also:
$_item = Mage::getModel('catalog/product')->load($product->getId());
//echo $_item->getData('ppuom');
//print_r($_item);
$simpleProduct = $_item->getOptionsByCode()['simple_product']->getItem()->getProduct();
print_r($simpleProduct);
Seems as if you were most of the way there. I've tested this on my Magento site and it worked for me. It's pretty simple actually, you just have to grab the right model for that collection. Also, it seems like you're changing the pricing?!?! Be careful that your wishlist items contain the necessary attributes used in your logic.
$_item = Mage::getModel('catalog/product')->load($product->getId());
$attribute1 = $_item->getData('attribute1_code'); //see admin for attribute code
$attribute2 = $_item->getData('attribute2_code'); //see admin for attribute code
OR
Make changes to your template's wishlist files rather than the pricing logic in the code folder. You'll have access to all the data you need and it won't interfere with the price.php file which is relied on heavily in the cart and other critical areas of the website. The price in the wishlist is recalculated when it's moved to the cart anyway.

Magento: How to hide child-categories products from being displayed on top category?

In magento, all products from a child-category is being displayed on top/parent categories. For example, i have this set of categories:
Fabric
- Cotton
---- Shirts (1)
--------Half Sleeves (5)
So in total i have 6 products, and when i click on fabric, it shows all 6 products along with sub-categories.
I don't want this, i want to only list categories and don't want to pull products from child-categories.
So, i want a method or way that can list only child-categories when i click Fabric. And only list 5 products when i click half-sleeves.
Btw, all of my categories are already set to Is Anchor = NO.
Here is the snippet from app/design/frontend/base/default/template/catalog/category/view.phtml
$_cat = new Mage_Catalog_Block_Navigation();
$curent_cat = $_cat->getCurrentCategory();
$curent_cat_id = $curent_cat->getId();
$parentId=Mage::getModel('catalog/category')->load($curent_cat_id)->getParentId();
$categoryid = $parentId;//$_category->getId();
$category = new Mage_Catalog_Model_Category();
$category->load($categoryid);
$collection = $category->getProductCollection();
$collection->addAttributeToSelect('*');
$i=0;
foreach ($collection as $_product) {........}
Any ideas?
Many Thanks!
hello Aamir Siddique try this function to get child every time, so when click on fabrics you have to pass id of fabrics to this function to get it's child category, here i am giving function so you can get children array,
function get_child($category_id)
{
$id=$category_id;
$i=0;
$children = Mage::getModel('catalog/category')->getCategories($id);
foreach ($children as $category)
{
$data["cat_data"][$i]["id"]=$category->getId();
$data["cat_data"][$i]["name"]=$category->getName();
$i++;
}
return $data;
}
Did you try change Display Mode of Fabric category to Static block only, then create a static block in which contains link to child categories?

Magento 1.6 copy category products

Heyhey,
I'm trying to make a script that will load all products from one category and add them to another category (so, basically, just link all products to an additional category). What I'm trying is:
$category = Mage::getModel('catalog/category');
$category->load($id); // Preset category id
$collection = $category->getProductCollection();
$collection->addAttributeToSelect('*');
foreach ($collection as $product) {
$result[] = $product->getProductId();
// Now get category ids and add a specific category to them and save?
}
$result comes up empty, and I have no idea how to proceed. Any ideas?
First thing to look at, don't select all attributes, $collection->addAttributeToSelect('id') is enough. Second to get product ID use
$product->getId();
To change the categories you could try something like this:
$categories = $product->getCategoryIds();
$categories[] = 4; // Category to add
$product->setCategoryIds($categories);
$product->save();

Magento - How to link the Configurable Product image to the Simple Product image?

This is the situation:
I have a configurable product with several simple products.
These simple products need to have the same product image as the configurable product.
Currently I have to upload the same image to each simple product over and over again.
Is there a way to link the product image of the configurable product to the simple products?
Some of my products have 30 simple products in 1 configurable product and it is overkill/annoying to upload the same image 30 times.
I hope someone can help me with this problem!
Thanks in advance!
Insert this into your DOCROOT\app\design\frontend\<pachage>\<theme>\template\catalog\product\view\media.phtml after $_product = $this->getProduct();
$_parentIdArray = Mage::getModel('catalog/product_type_configurable')->getParentIdsByChild($_product->getId());
if(sizeof($_parentIdArray)==1 && Mage::getModel('catalog/product')->load($_parentIdArray[0])->getTypeId() == 'configurable'){
$_product = Mage::getModel('catalog/product')->load($_parentIdArray[0]);
}
That will use the images belonging to the parent configurable product if the simple product has a single parent of type configurable.
EDIT
To use this in the list view, open DOCROOT\app\design\frontend\<pachage>\<theme>\template\catalog\product\list.phtml and insert the same code block in 2 locations:
line 45 after <?php foreach ($_productCollection as $_product): ?> (inside the <?php ?> wrappers)
line 106 (approx, might be different in your theme) after <?php $i=0; foreach ($_productCollection as $_product): ?>
Both locations are required to deal with the grid view and list view versions of the page.
HTH,
JD
I believe that the right way to do this is to override the image helper (app/core/Mage/Catalog/Helper/Image.php), so that in the init function, you check if you have a simple product, and if you do, replace that with the configurable product. This should effect the change for ALL templates.
A quick workaround might be to export your product list (Admin > System > Import/Export > Profiles), put the image file name in the appropriate column(s) for all your simple products, copy the file(s) to media/import/ directory then import the modified product list. The various associations will be made for you and the image file(s) will be copied to wherever they need to be.
I think the best way is to override catalog image helper (like #stew said). To avoid performance issues we can use raw sql queries to fetch parent's image value:
class Wfs_Catalog_Helper_Image extends Mage_Catalog_Helper_Image
{
public function init(Mage_Catalog_Model_Product $product, $attributeName, $imageFile=null)
{
parent::init($product, $attributeName, $imageFile);
if (!$product->getId() || $imageFile || $product->isConfigurable()) {
return $this;
}
$productImage = $product->getData($attributeName);
if (!$productImage || $productImage == 'no_selection') {
// Get parent product's attribute
$value = $this->getParentProductAttribute($product->getId(), $attributeName);
if ($value) {
$this->_getModel()->setBaseFile($value);
}
}
return $this;
}
public function getParentProductAttribute($productId, $attributeName)
{
$coreResource = Mage::getSingleton('core/resource');
$conn = $coreResource->getConnection('core_read');
$attrId = Mage::getSingleton('eav/config')
->getAttribute(Mage_Catalog_Model_Product::ENTITY, $attributeName)
->getId();
$select = $conn->select()
->from(array('rel' => $coreResource->getTableName('catalog/product_relation')), array())
->join(
array('var' => $coreResource->getTableName('catalog_product_entity_varchar')),
'var.entity_id = rel.parent_id',
array('value')
)
->where('rel.child_id = ?', $productId)
->where('var.attribute_id = ?', $attrId);
return $conn->fetchOne($select);
}
}

Magento: using getModel to get product and category

I have some code that returns an array of product details including a url_path. To create a link to this product I have to know the category and subcategory of the product. Unfortunately out all the data this method returns neither the category or sub category are pulled out.
Here is the code I have that gets a product:
$product_id = array(231, 230,229,228);
foreach ($product_id as $id){
$productDetails = Mage::getModel('catalog/product')->load($id)->getData();
echo $productDetails['url_path'].'<br />';
}
Is it possible to get the category and subcategory for each product?
you are looking for
foreach ($product_id as $id){
$categoryIds = Mage::getModel('catalog/product')->load($id)->getCategoryIds();
}
which will return you an array of category ids that the product belongs to.
Better way not to miss something with rewrites is to use core functionality.
Mage_Catalog module has own url model, with which product urls can be modified.
So, the code will be:
$product_id = array(231, 230,229,228);
$urlModel = Mage::getSingleton('catalog/url');
foreach ($product_id as $id) {
$urlModel->refreshProductRewrite($id);
}
And it is no need to retrieve category ids for this purpose.

Categories