How to get url of a category in magento - magento

am trying to display all the second level categories and my code is
<?php $storeId = Mage::app()->getStore()->getId();
//Get category model
$_category = Mage::getModel('catalog/category')->setStoreId($storeId);
$_categoryCollection = $_category->getCollection();
$_categoryCollectionIds = $_categoryCollection->getAllIds();
//Remove root category from array
unset($_categoryCollectionIds[0], $_categoryCollectionIds[1]);
?>
<div id="accordian_hover">
<?php
$o = null;
$o .= '<ul>';
foreach ($_categoryCollectionIds as $catId) {
$_category = $_category->load($catId);
if($_category->getLevel() == 2) {
$catChildren = $_category->getChildren();
if(!empty($catChildren)) {
$o .= '<li> '.$_category->getName().'';
$o .= '<ul>';
$categoryChildren = explode(",", $catChildren);
foreach ($categoryChildren as $categoryChildId) {
/* #var $_childCategory Mage_Catalog_Model_Category */
$_childCategory = $_category = Mage::getModel('catalog/category')->setStoreId($storeId)->load($categoryChildId);
$o .= '<li>'.$_childCategory->getName().'</li>';
// If you wish to display the total number of products for each category, uncomment this line
// $o .= '<span class="totalNumberOfProducts">'.$_childCategory->getProductCollection()->count().'</span>';
}
$o .= '</ul></li>';
}
}
} $o .='</ul>';
echo $o;
?>
</div>
But the top menu url is wrong all other are displaying correct but the main category url is wrong(2nd category) Please help me , and i have to display the third level menu also when the user hover on category...
Live Link http://toolskaart.com/

Hope the below code will solve your problem.
Mage::getModel('catalog/category')->load($_category->getId())->getUrl()
It works for me.

Related

get all Categories and SubCatgories without loading model in foreach loop

I want to display all categories and their subcategories in primary nav menu.
When i hover on cateory, it should display its subcategories.
I want to implement this functionality without loading Mage::getModel('catalog/category') in foreach loop.
as you want to write code in phtml file use below code which create tree structure of category.
<ul>
<?php
$obj = new Mage_Catalog_Block_Navigation();
$storeCategories = $obj->getStoreCategories();
Mage::registry('current_category') ? $currentCategoryId = Mage::registry('current_category')->getId() : $currentCategoryId='';
foreach ($storeCategories as $_category):
?>
<li>
<strong><?php echo $_category->getName(); ?></strong>
<?php $categoryChildren = $_category->getChildren(); ?>
<?php if($categoryChildren->count()) : ?>
<ul>
<?php foreach($categoryChildren as $_categoryChild) : ?>
<?php $_categoryChildModel = Mage::getModel('catalog/category')->load($_categoryChild->getId());?>
<?php $categoryGrandchildren=$_categoryChild->getChildren(); ?>
<li>
<?php
$currentCategoryId===$_categoryChild->getId() ? $bold="style=\"font-weight:bold\"" : $bold='';
echo ' ' . '<a href="' . $_categoryChildModel->getUrl() . '"' . $bold . '>' . $_categoryChild->getName() . '(' . $_categoryChildModel->getProductCollection()->count() . ')</a>';
?>
</li>
<?php if($categoryGrandchildren->count()) : ?>
<?php foreach($categoryGrandchildren as $_categoryGrandchild) : ?>
<?php $_categoryGrandchildModel = Mage::getModel('catalog/category')->load($_categoryGrandchild->getId());?>
<li>
<?php
$currentCategoryId===$_categoryChild->getId() ? $bold="style=\"font-weight:bold\"" : $bold='';
echo '  ' . '<a href="' . $_categoryGrandchildModel->getUrl() . '"' . $bold . '>' . $_categoryGrandchild->getName() . '(' . $_categoryGrandchildModel->getProductCount() . ')</a>';
?>
</li>
<?php endforeach; ?>
<?php endif; ?>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</li>
<?php endforeach ?>
</ul>
and using css and HTML you can achieve your goal to display sub menu on hover of main menu.
Still let me if you need any other help.
Thanks
ok so I just did this and I figured I'd search to see if anyone was wondering how to achieve this. The trick to this is
Mage::getResourceSingleton('catalog/category')->getAttributeRawValue($categoryEntityId,array('name','level','url_key','path','is_active'),Mage::app()->getStore());
This does not load the category model lets take a look at what it is actually doing.
Go to app/code/core/Mage/Catalog/Model/Resource/Abstract
public function getAttributeRawValue($entityId, $attribute, $store)
{
if (!$entityId || empty($attribute)) {
return false;
}
if (!is_array($attribute)) {
$attribute = array($attribute);
}
$attributesData = array();
$staticAttributes = array();
$typedAttributes = array();
$staticTable = null;
$adapter = $this->_getReadAdapter();
foreach ($attribute as $_attribute) {
/* #var $attribute Mage_Catalog_Model_Entity_Attribute */
$_attribute = $this->getAttribute($_attribute);
if (!$_attribute) {
continue;
}
$attributeCode = $_attribute->getAttributeCode();
$attrTable = $_attribute->getBackend()->getTable();
$isStatic = $_attribute->getBackend()->isStatic();
if ($isStatic) {
$staticAttributes[] = $attributeCode;
$staticTable = $attrTable;
} else {
/**
* That structure needed to avoid farther sql joins for getting attribute's code by id
*/
$typedAttributes[$attrTable][$_attribute->getId()] = $attributeCode;
}
}
/**
* Collecting static attributes
*/
if ($staticAttributes) {
$select = $adapter->select()->from($staticTable, $staticAttributes)
->where($this->getEntityIdField() . ' = :entity_id');
$attributesData = $adapter->fetchRow($select, array('entity_id' => $entityId));
}
/**
* Collecting typed attributes, performing separate SQL query for each attribute type table
*/
if ($store instanceof Mage_Core_Model_Store) {
$store = $store->getId();
}
$store = (int)$store;
if ($typedAttributes) {
foreach ($typedAttributes as $table => $_attributes) {
$select = $adapter->select()
->from(array('default_value' => $table), array('attribute_id'))
->where('default_value.attribute_id IN (?)', array_keys($_attributes))
->where('default_value.entity_type_id = :entity_type_id')
->where('default_value.entity_id = :entity_id')
->where('default_value.store_id = ?', 0);
$bind = array(
'entity_type_id' => $this->getTypeId(),
'entity_id' => $entityId,
);
if ($store != $this->getDefaultStoreId()) {
$valueExpr = $adapter->getCheckSql('store_value.value IS NULL',
'default_value.value', 'store_value.value');
$joinCondition = array(
$adapter->quoteInto('store_value.attribute_id IN (?)', array_keys($_attributes)),
'store_value.entity_type_id = :entity_type_id',
'store_value.entity_id = :entity_id',
'store_value.store_id = :store_id',
);
$select->joinLeft(
array('store_value' => $table),
implode(' AND ', $joinCondition),
array('attr_value' => $valueExpr)
);
$bind['store_id'] = $store;
} else {
$select->columns(array('attr_value' => 'value'), 'default_value');
}
$result = $adapter->fetchPairs($select, $bind);
foreach ($result as $attrId => $value) {
$attrCode = $typedAttributes[$table][$attrId];
$attributesData[$attrCode] = $value;
}
}
}
if (sizeof($attributesData) == 1) {
$_data = each($attributesData);
$attributesData = $_data[1];
}
return $attributesData ? $attributesData : false;
}
As you can see no model loading happening just retrieving specific pieces of info. Also being part of the resource abstract means all catalog resource models (I haven't checked other resource models but, I wouldn't be too surprised to find this in others) have this available.
If you use this in an override of Mage_Catalog_Block_Navigation you can then call all of the info you need about any category without loading the model. To traverse the tree however, you have to do terrible things.
You can use 'path'(explode on /) to easily retrieve parents but you will need to get dirty in order to retrieve children categories so something like this to get Children.
$childrenQuery = "SELECT entity_id FROM catalog_category_entity WHERE path REGEXP '^.*\/" . $categoryId . "\/[[:digit:]]?[[:digit:]]?[[:digit:]]?[[:digit:]]?$'";
$resource = Mage::getSingleton('core/resource');
$readCxn = $resource->getConnection('core/read');
$children = $readCxn->fetchAll($childrenQuery);
if ($children[0]) {
return $children;
} else {
return;
}
The overall difficulty is that all model and resource model functions will expect an instance of a category object to make them all work with just the entity_id is definitely possible just a pain.
So I would not recommend doing this in general the only reason I did this is because the default magento root category in my case was not the actual functional root of categories (fun eh). If you are using a standard root category I would recommend using the Helper functions and retrieving the info from cache.
Either way from here all you have to do complete your functions in Mage_Catalog_Block_Navigation and assemble your menu in a template. And there you go; complete category menu without ever accessing a model->load.
Try This Code
<?php
require_once("app/Mage.php");
Mage::app();
function getChildCategories($category, $First = false) {
$sub = $First ? $category : $category->getChildren();
foreach ($sub as $child) {
$_categories[] = [ "name" => $child->getName(), "id" => $child->getId(), "children" => getChildCategories($child) ];
}
return $_categories;
};
function CategoriesTree($category, $First = false) {
$sub = $First ? $category : $category->getChildren();
echo "<pre>";
foreach ($sub as $child) {
echo $child->getName(); ;
CategoriesTree($child);
}
}
$_categories = Mage::helper('catalog/category')->getStoreCategories();
$categories = getChildCategories($_categories, true);
CategoriesTree($_categories, true);
?>

How to get current categorys root parent category and all its sub category

I need logic to show the category tree like below:
Cat1 -> cat11 -> cat111
Cat2 -> cat21 -> cat211
Cat3 -> cat31 -> cat311
So if I am in cat211, in the left column all the categories of its root parent category (Cat2) should be displaying. Eg. in magento
Cat2 -> Cat21 -> Cat211
The attribute path contains all parent ids in the form 1/root_id/parent_id/.../category_id. You can use $category->getPathIds() to retrieve it as an array (or $category->getParentIds() if you want to exclude the id of the category itself). Because the first id in the path is always "1", you should remove the first array item to start from the store root category:
$categoryIds = $category->getPathIds();
array_shift($categoryIds);
Then you can load these at once, using a collection:
$categoryCollection = $category->getCollection()->addIdFilter($categoryIds);
foreach ($categoryCollection as $categoryInPath) {
// do what you want with $categoryInPath
}
I guess you mean the category tree, And this should give you category tree. you can see the various filters being applied. (You can always do according to your need.)
<?php
$rootCatId = Mage::app()->getStore()->getRootCategoryId();
$catlistHtml = getTreeCategories($rootCatId, false);
echo $catlistHtml;
function getTreeCategories($parentId, $isChild){
$allCats = Mage::getModel('catalog/category')->getCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('is_active','1')
->addAttributeToFilter('include_in_menu','1')
->addAttributeToFilter('parent_id',array('eq' => $parentId))
->addAttributeToSort('position', 'asc');
$class = ($isChild) ? "sub-cat-list" : "cat-list";
$html .= '<ul class="'.$class.'">';
foreach($allCats as $category)
{
$html .= '<li><span>'.$category->getName()."</span>";
$subcats = $category->getChildren();
if($subcats != ''){
$html .= getTreeCategories($category->getId(), true);
}
$html .= '</li>';
}
$html .= '</ul>';
return $html;
}
?>
EDIT: getting all parent category using an id/current category id..
$id = Mage::registry('current_category'); //or if you are retrieving other way around
$category = Mage::getModel('catalog/category')->load($id);
$categorynames = array();
foreach ($category->getParentCategories() as $parent) {
$categorynames[] = $parent->getName();
}
print_r($categorynames); //dumping category names for eg.

Magento - Check if subcategory exists in current category

I have the following category setup in my magento store:
store root
|
bedroom kitchen bathroom
| | |
furniture furniture furniture
lighting lighting misc
misc
I need to be able to check if the category misc exists as a subcategory in my current category or not, and if so show a particular block.
So if i was in the kitchen category it would not show but in bedroom and bathroom it would.
How can i do this this check?
To get your sub-category misc
$currentCategoryId = 10;
$collection = Mage::getModel('catalog/category')->getCollection()
->addAttributeToFilter('is_active', 1) //only active categories
->addAttributeToFilter('parent_id', $currentCategoryId)
->addAttributeToFilter('name', 'misc');
To check if your collection contains at least 1 record in it:
if ($collection->getSize() > = 1) {
//'misc' sub-category exists
}
else {
//'misc' sub-category does not exists
}
Load you current category using and get its Id
$currentCat = Mage::registry('current_category');
$currentCatId = $currentCat->getId();
Load the 'misc' sub-category using
$_category = Mage::getModel('catalog/category')->loadByAttribute('name', 'misc');
$_categoryParentId = $_category->getParentCategory()->getId();
if( $currentCatId == $_categoryParentId){
//Do your stuffs
}
Though you have two categories with the same name misc, so you would want to laod category by url-key or parse through the multiple category array to test.
Try flollowing,
<?php
$categoryId = 5;
$categories = Mage::getModel('catalog/category')->load($categoryId)->getChildren();
$catAsArray = explode(',', $categories);
//you can have $catAsArray to check if it has subcategories
foreach($catAsArray as $child)
{
$_child = Mage::getModel( 'catalog/category' )->load( $child );
echo $_child->getName() . '<br />';
echo $_child->getUrl() . '<br />';
echo $_child->getDescription() . '<br />';
}
?>
Or the other way,
<?php
$categoryId = 5;
$_category = Mage::getModel('catalog/category')->load($categoryId);
if($_category->hasChildren())
{
}
?>

Magento navigation-block issues

How can I set the subcategories to be visible at all times in main navigation block (left column)? Once I start browsing the subcategories of any category, the navigation block is showing only the top categories. Example at www.valikoi.com.
Regards, Tommi
I think this will help you,
<ul class="catlist">
<?php
$obj = new Mage_Catalog_Block_Navigation();
$store_cats = $obj->getStoreCategories();
$current_cat = $obj->getCurrentCategory();
$current_cat = (is_object($current_cat) ? $current_cat->getName() : '');
$currentCategory = Mage::registry('current_category');
foreach ($store_cats as $cat) {
if ($cat->getName() == $current_cat) {
//enters and lists all main categories
echo '<li class="current">
'.$cat->getName()."\n<ul>\n";
//get the child category of a current category
foreach ($obj->getCurrentChildCategories() as $subcat) {
echo '<li>
'.$subcat->getName()."</li>\n";
}
echo "</ul>\n</li>\n";
} else {
//enters when a sub category is clicked and lists all main categories
echo '<li>
'.$cat->getName()." </li>\n";
//this is to load the categories like in admin order
$loadCategory= Mage::getModel('catalog/category')->getCategories($currentCategory->getParentId(),0, true, true);
//below code did not work to load categories like in admin order
//$explod= $loadCategory->getChildrenCategories('position','asc');
//$subCategories = explode(',', $explod);
if (($currentCategory->getParentId() == $cat->getId()) )
{
//enters when a sub category is clicked and loads its parent and show its subcategories
echo '<ul class="catlist_inner">';
foreach ($loadCategory as $subCategoryId)
{
if($subCategoryId->getIsActive())
{
echo '<li>
'.$subCategoryId->getName().' </li>';
}
}
echo '</ul>';
}
}
}
?>
</ul>

magento category search

I have two main child under navigation in category tree as below images
I want to list category and subcategories for either Region or Activities, I have tried two different function for that
$collection = Mage::getModel('catalog/category')->getCollection()->addAttributeToSelect('name')->load();
foreach ($collection as $cat) {
echo $cat->getName();
}
this will return all child from both Region and Actities and another function
$children = Mage::getModel('catalog/category')->getCategories(10);
foreach ($children as $category) {
echo $category->getName();
}
Reference link
this return only subcategories
I want to list all category, sub-categories and sub-subcategory and so on... for Region
Thank in advance
Try this one:
$rootcatId= 10;
$categories = Mage::getModel('catalog/category')->getCategories($rootcatId);
function get_categories($categories) {
$array= '<ul>';
foreach($categories as $category) {
$cat = Mage::getModel('catalog/category')->load($category->getId());
$count = $cat->getProductCount();
$array .= '<li>'.
'<a href="' . Mage::getUrl($cat->getUrlPath()). '">' .
$category->getName() . "(".$count.")</a>\n";
if($category->hasChildren()) {
$children = Mage::getModel('catalog/category')->getCategories($category->getId());
$array .= get_categories($children);
}
$array .= '</li>';
}
return $array . '</ul>';
}
echo get_categories($categories);

Resources