Magento - browse 4 tier category tree - php

I'm trying to build some code on my magento site that will allow the customer to click through my product categories viewing the child categories on each consecutive page.
I have a code snippet below that will successfully works for the first 2 levels, but does not allow me to browse the childern of the second level (i.e.the 3rd level etc)
Can anyone assist in tweaking this code to allow me to browse 4 levels deep?
<?php
$obj = new Mage_Catalog_Block_Navigation();
$store_cats = $obj->getStoreCategories();
$current_cat = $obj->getCurrentCategory();
$current_cat = (is_object($current_cat) ? $current_cat->getName() : '');
foreach ($obj->getCurrentChildCategories() as $subcat) {
echo '<li>'.$subcat->getName()."</li>\n";
}
echo "</ul>\n</li>\n";
?>

You need to add recursively the $obj->getCurrentChildCategories() for the child categories aswell, since your current foreach only iterates for the childs of the first one.
Store the foreach in a function and use it for the $cat object.
function cats($obj) {
foreach ($obj->getCurrentChildCategories() as $subcat) {
echo '<li>'.$subcat->getName()."</li>\n";
cats($subcat);
}
}

Related

How to target different levels of a Wordpress taxonomy?

I'm trying to dynamically target different levels of a taxonomy that are setup like this:
Top Level Category
-- Second Level Category
--- Third Level Category
I've targeted the first and second levels like this:
<?php $parent = get_queried_object()->parent;
if($parent == "0"){ ?>
Top level
<?php } else { ?>
Second level
<?php } ?>
How can I target the third level?
<?php $term_id = get_queried_object()->term_id;
$ancestors = get_ancestors( $term_id, 'categories' ); ?>
<pre>
<?php print_r($ancestors); ?>
</pre>
When on a category page with the code above... top level shows the array as empty, second level shows the id of the parent, third level shows the array with two levels. How can I target each individual level?
Try with get_ancestors() WP function : get_ancestors()
function get_tax_level($id, $tax){
$ancestors = get_ancestors($id, $tax);
return count($ancestors)+1;
}
$current_term_level = get_tax_level(get_queried_object()->term_id, get_queried_object()->taxonomy);
if ($current_term_level = 0) {
// show first drop-down
} else if ($current_term_level = 1) {
// show second drop-down
} else {
// show third drop-down
}

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?

Wordpress category display child only one level

I'm trying to make a theme which shows an overview of child categories with title, link and description when entering a category archive. However, I only want to show child categories one level below the current category, and not the children of child categories.
How do I do that?
<?php
global $ancestor;
$childcats = get_categories('child_of=' . $cat . '&hide_empty=1');
foreach ($childcats as $childcat) {
if (cat_is_ancestor_of($ancestor, $childcat->cat_ID) == false){
echo '<li><h2><a href="'.get_category_link($childcat->cat_ID).'">';
echo $childcat->cat_name . '</a></h2>';
echo '<p>'.$childcat->category_description.'</p>';
echo '</li>';
$ancestor = $childcat->cat_ID;
}
}
?>
I found that code, but it only returns one child. It returns. (Faa and Faq are child categories)
Faa
Faq -- Not displayed
Thanks!
Make sure 'FAQ' has post under it. If you notice the "code you found" is passing the parameter "&hide_empty=1" which means it will not return categories that are empty.
So your options are to either remove that or make sure your category has posts under it.

Magento display subcategory of specific current parent category PHP

I'm trying to display brands on my store. I sell both men and women clothing so I have two separate brand categories.
My category structure looks like this:
Men
Brands
x-brand
Women
Brands
y-brand
I would like to display the brand of the product.
I found this code:
$children = Mage::getModel('catalog/category')->getCategories(10);
foreach ($children as $category) {
echo $category->getName();
}
However, it works for only one category and displays all subcategories in the parent category not the one owned by the product.
How can I modify this to show the subcategory of the current brand category.
I hope this made sense and I appreciate any help!
To display sub-category listing for a give category
$_category = Mage::registry('current_category');
$subcategories = Mage::getModel('catalog/category')->getCategories($_category->getId());
foreach ($subcategories as $subcategory){
print_r($subcategory->getData()
}
See more # Magento: Display sub-category list
Old question is old, but figured I'd chime in as the question went unanswered and someone else might find this useful..
So, first of all, this code relies on being inside a products list loop, i.e.:
$_productCollection=$this->getLoadedProductCollection();
foreach ($_productCollection as $_product) {
*... your product list output here ...*
}
Second, this code is dependent on a setup using "BRANDS" as a sub-category of your Magento root category (whatever it happens to be called) and each brand name being set as a sub-category of the "BRANDS" sub-cat. You may need to augment that cat name in the code below or change your category structure to match mine.
So, within the "ProductCollection" loop already set in app/design/frontend/your-package/your-theme/template/catalog/product/list.phtml, you can put this snippet to echo the name of the brand name.
$categories = $_product->getCategoryCollection()
->addAttributeToSelect('name')
->addAttributeToFilter('is_active', array('eq' => 1));
foreach($categories as $category) {
$catID = $category->getId();
$catParent = Mage::getModel('catalog/category')->load($catID)
->getParentCategory();
if ( $catParent->getName() == 'BRANDS' ) {
echo ''.$category->getName().'';
}
}
Bonus edit:
Added code to wrap brand name in link to brand category page.

Copy and Paste Category in Magento

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();
}
?>

Categories