I need help. I use this code to get the category link under products info on a few pages in Magento:
<?php $categories = $_product->getCategoryIds(); ?>
<span>In </span>
<?php $i=1; foreach($categories as $k => $_category_id): ?>
<?php if($i>1) {break;} ?>
<?php $_category = Mage::getModel('catalog/category')->load($_category_id) ?>
<a class="in-category" href="<?php echo $_category->getUrl() ?>"><?php echo $_category->getName() ?></a>
<?php $i++; endforeach; ?>
You can see it here: http://192.241.178.130/new_arrivals
Problem I'm having is that I want the script to display the category closest to the product but it's instead displaying the root category (Default category of the site)
M
Thanks.
Try something like this:
<?php
$categoryIds = $_product->getCategoryIds();
$categories = Mage::getModel('catalog/category')
->addAttributeToSelect('url_key')//add url key to select
->addAttributeToSelect('name')//add name to select
->getCollection() //get categories as collection
->addAttributeToFilter('entity_id', $categoryIds)//filter only by selected ids
->addAttributeToFilter('is_active', 1)//get only active categories
->addAttributeToFilter('level', array('gte'=>2))//ignore root category and 'root of roots'
->setOrder('level', 'desc');//sort by level descending
$mainCategory = $categories->getFirstItem();//get only the category lowest in the tree
if ($mainCategory->getId()) : ?>
<a class="in-category" href="<?php echo $mainCategory->getUrl() ?>"><?php echo $mainCategory->getName() ?></a>
<?php endif;?>
Instead of using a foreach to walk one time through the array you can use array_pop.
Anyhow the function getCategoryIds() will return an array of all categories the product is in. This also include parent categories and are in logical order. The category with the lowest id will show up first.
Perhaps something like this will work for you:
<?php $_category_id = array_pop($_product->getCategoryIds()); ?>
<span>In </span>
<?php $_category = Mage::getModel('catalog/category')->load($_category_id) ?>
<a class="in-category" href="<?php echo $_category->getUrl() ?>">
<?php echo $_category->getName() ?>
</a>
Related
So I'm using this code to display the categories that any product on my website is included in. The issue is that I'm using some categories as placeholders to show 'featured products' I wanted to try to filter these out.
This is Magento 1.9.1.0 on PHP 5.6.30
<ul class="listfix">
<?php $categories = $_product->getCategoryIds(); ?>
<?php foreach($categories as $k => $_category_id):
?>
<?php $_category= Mage::getModel('catalog/category')->load($_category_id)?>
<?php if($_category->getId()):?>
<li><a href="<?php echo $_category->getUrl() ?>"><?php echo $_category-
>getName() ?></a>
</li>
<?php endif;?>
<?php endforeach; ?>
</ul>
I tried adding this
$_category->addAttributeToFilter('is_active', 1)//get only active
categories
but it threw an error, I'm not a great php guy, I just find pieces of code and try to make them work. I got the original parts from HERE
as per below I've tried to add in the code that follows but I'm still seeing categories listed that are not active...
<ul class="listfix">
<?php $activeCategories =
Mage::getResourceModel('catalog/category_collection')
->addAttributeToFilter('is_active', 1)
->getColumnValues('entity_id');
?>
<?php $activeCategories = $_product->getCategoryIds(); ?>
<?php foreach($activeCategories as $k => $_category_id): ?>
<?php $_category= Mage::getModel('catalog/category')->load($_category_id)?>
<?php if($_category->getId()):?>
<li><a href="<?php echo $_category->getUrl() ?>"><?php echo $_category-
>getName() ?></a>
</li>
<?php endif;?>
This will give you a list of all the active Categor ID's in 1.9:
$activeCategories = Mage::getResourceModel('catalog/category_collection')
->addAttributeToFilter('is_active', 1)
->getColumnValues('entity_id');
Then you loop through that array, and load the category, or whatever, by ID:
foreach($activeCategories as $id) {
$cat = Mage::getModel('catalog/category')->load($id);
}
<ul class="listmem">
<?php $activeCategories =
Mage::getResourceModel('catalog/category_collection')
->addAttributeToFilter('is_active', 1)
->getColumnValues('entity_id');?>
<ul class="listfix">
<?php $activeCategories = $_product->getCategoryIds(); ?>
<?php foreach($activeCategories as $id) {
$cat = Mage::getModel('catalog/category')->load($id);
} ?>
<?php if($cat->getId()):?>
<li><a href="<?php echo $cat->getUrl() ?>"><?php echo $cat->getName() ?>
</a>
</li>
<?php endif;?>
</ul>
I thought I sorted out what I was doing wrong, but I'm still seeing the categories that aren't active in my list.
I'm using Luxury theme in Magento. I'm trying to display current category name in the catalog/category/view.phtml file.
What I have done so far:
<div class="custom">
<?php if($crumbs && is_array($crumbs)): ?>
<div class="container">
<div class="col-md-12">
<ul>
<?php foreach($crumbs as $_crumbName=>$_crumbInfo): ?>
<li class="<?php echo $_crumbName ?>" <?php if(Mage::getStoreConfig('mgs_theme/general/snippets') == 1): ?> itemscope itemtype="http://data-vocabulary.org/Breadcrumb" <?php endif ?>>
<?php if($_crumbInfo['link']): ?>
<a href="<?php echo $_crumbInfo['link'] ?>" title="<?php echo $this->escapeHtml($_crumbInfo['title']) ?>" <?php if(Mage::getStoreConfig('mgs_theme/general/snippets') == 1): ?> itemprop="url" <?php endif ?>><span <?php if(Mage::getStoreConfig('mgs_theme/general/snippets') == 1): ?> itemprop="title" <?php endif ?>><?php echo $this->escapeHtml($_crumbInfo['label']) ?></span></a>
<?php else: ?>
<strong><span <?php if(Mage::getStoreConfig('mgs_theme/general/snippets') == 1): ?> itemprop="title" <?php endif ?>><?php echo $this->escapeHtml($_crumbInfo['label']) ?></span></strong>
<?php endif; ?>
<?php if(!$_crumbInfo['last']): ?>
<span>| </span>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
</div>
</div>
<?php endif ?>
</div>
I have taken this code from page/html/breadcrumbs.phtml.
I am totally new to Magento/PHP. It doesn't show any error but it's not displaying the name of the category, while it's visible in breadcrumbs header. What I am doing wrong here?
If you want to show category name on category page. You can achieve this by 2 ways.
<?php echo $this->getCurrentCategory()->getName(); ?>
Or
<?php echo Mage::registry('current_category')->getName() ?>
On our site (magento 1.9) we wanted to show the first parent category of the current product on our product pages and provide a link to it. I achieved this as follows - you should be able to reverse engineer my code to your own ends.
At first I did it by adding the following code directly to the catalog/product/view.phtml but have since migrated it into a custom helper in my own module.
Here's the code, see if it works for you.
//get an array of the IDs of every category to which the product belongs.
$categoryIds = $_product->getCategoryIds();
//set CatID to the second element of the array since the first element
//is the base category of which all others are children.
$_catID = $categoryIds[1];
//load the correct model
$_category = Mage::getModel('catalog/category')->load($_catID);
//get the level of the current category
$level = $_category->getLevel();
//This if statement prevents the function from trying to run on products
//which are not assigned to any category.
if($_category->getName()){
// we want the second level category, since the first is the base category.
// ie if we call the default category 'base' and the product is in category
//base->foo->bar->baz we want to return the link to foo.
// while current category is deeper than 2 we ask it for it's parent
//category until we reach the one we want
while ($level > 2){
$parent = $_category->getParentId();
$_category =Mage::getModel('catalog/category')->load($parent);
$level = $_category->getLevel();
}
//Now we can build the string and echo it out to the page
$caturl = $_category->getUrl_key();
$_linkstring = 'http://www.yourwebsite.com/' . $caturl . '.html';
echo 'in category:';
echo '<a href="' . $_linkstring . '" title="'. $_category->getName() .'">';
echo ' '. $_category->getName();
echo '</a>';
}
Get the category name, image, description from category id in magento
$category = Mage::getModel('catalog/category')->load(category_id);
echo $category->getName();
echo $category->getImageUrl();
echo $category->getDescription();
Please put the category id in the load function
I am trying to display the number of products in each category, using this code to I want to display subcategories of category id:3 . It is showing but it included disabled and invisible products.
<?php
$cats = Mage::getModel('catalog/category')->load(3)->getChildrenCategories();
?>
<ul>
<?php foreach($cats as $category): ?>
<li>
<?php echo $category->getName() ?>(<?php echo $category->getProductCount(); ?>)
</li>
<?php endforeach; ?>
</ul>
Is there any good solution so that I can get the exact count of categories that are Enabled and active.
you need check active filter acondition and for this you can use below code
$products = Mage::getModel('catalog/category')->load($category->getId())
->getProductCollection()
->addAttributeToSelect('entity_id')
->addAttributeToFilter('status', 1)
->addAttributeToFilter('visibility', 4);
echo $products->count();
Without any regard to Magento programming conventions, that piece of code should look like this:
<?php
$cats = Mage::getModel('catalog/category')->load(3)->getChildrenCategories();
$collection = Mage::getModel('catalog/product')->getCollection();
Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($collection);
Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($collection);
?>
<ul>
<?php foreach($cats as $category): ?>
<?php $count = $collection->addCategoryFilter($category)->getSize(); ?>
<li>
<?php echo $category->getName() ?>(<?php echo $count ?>)
</li>
<?php endforeach; ?>
</ul>
But do the world a favor and organize the code properly.
Loading collection and using multiple attribute filter is not a proper way and this won't filter associated product and it's stock levels.
This piece of code with do all together,
$categoryId = 32; // Replace with your category
$category = Mage::getModel('catalog/category')
->setStoreId(Mage::app()->getStore()->getId())
->load($categoryId);
Mage::register('current_category', $category);
$products = Mage::getSingleton('catalog/layer')->getProductCollection();
echo $products->getSize();
I'm displaying a list of sub categories by parent category ID and am wanting to display the category image in place of a category name.
Here is what I have so far...
<div id="menu_brands">
<div class="brand_head">
<h3><?php echo $this->__('Browse By Brand') ?></h3>
</div>
<div class="brand_list">
<?php
$cats = Mage::getModel('catalog/category')->load(6)->getChildren();
$catIds = explode(',',$cats);
$categories = array();
foreach($catIds as $catId) {
$category = Mage::getModel('catalog/category')->load($catId);
$categories[$category->getName()] = $category->getUrl();
$img = $category->getImageUrl(); //I suspect this line is wrong
}
ksort($categories, SORT_STRING);
?>
<ul>
<?php foreach($categories as $name => $url): ?>
<li>
<!--<?php echo $name; ?>-->
<a href="<?php echo $url; ?>" title="<?php echo $name; ?>">
<img src="<?php echo $img; ?>" width="auto" alt="<?php echo $name; ?>" /> <!--I suspect this line is wrong-->
</a>
</li>
<?php endforeach; ?>
</ul>
</div>
</div>
I've tried countless ways to display the images in place of the category names but nothing seems to make the images appear. Currently with the above, the output is an empty 'img src' so there is clearly an error with what I'm trying (and probably a better way of achieving what I'm after).
Please could someone kindly point out what the problem is?
If it's of any relevance, what I intend to do afterwards is then display the category images in a grid format (3 or 4 per line).
Many thanks in advance.
The solution by zigojacko is not ideal because it separately loads in models in a loop. This does not scale well, and with many categories will thrash your database. Ideally, you'd add the images to the child collection.
A faster solution is to add the image attribute to a collection with an ID filter like B00MER:
// Gets all sub categories of parent category 'Brands'
$parent = Mage::getModel('catalog/category')->load(6);
// Create category collection for children
$childrenCollection = $parent->getCollection();
// Only get child categories of parent cat
$childrenCollection->addIdFilter($parent->getChildren());
// Only get active categories
$childrenCollection->addAttributeToFilter('is_active', 1);
// Add base attributes
$childrenCollection->addAttributeToSelect('url_key')
->addAttributeToSelect('name')
->addAttributeToSelect('all_children')
->addAttributeToSelect('is_anchor')
->setOrder('position', Varien_Db_Select::SQL_ASC)
->joinUrlRewrite();
// ADD IMAGE ATTRIBUTE
$childrenCollection->addAttributeToSelect('image');
?>
<ul>
<?php foreach($childrenCollection as $cat): ?>
<li>
<a href="<?php echo $cat->getURL(); ?>" title="<?php echo $cat->getName(); ?>">
<img class="cat-image" src="<?php echo $cat->getImageUrl(); ?>" />
</a>
</li>
<?php endforeach; ?>
</ul>
We managed to resolve this ourselves - see fix below.
<?php
//gets all sub categories of parent category 'Brands'
$cats = Mage::getModel('catalog/category')->load(6)->getChildren();
$catIds = explode(',',$cats);
$categories = array();
foreach($catIds as $catId) {
$category = Mage::getModel('catalog/category')->load($catId);
$categories[$category->getName()] = array(
'url' => $category->getUrl(),
'img' => $category->getImageUrl()
);
}
ksort($categories, SORT_STRING);
?>
<ul>
<?php foreach($categories as $name => $data): ?>
<li>
<a href="<?php echo $data['url']; ?>" title="<?php echo $name; ?>">
<img class="cat-image" src="<?php echo $data['img']; ?>" />
</a>
</li>
<?php endforeach; ?>
</ul>
Surprised we didn't get more support on this with it being a relatively simple Magento issue. Thanks B00MER for your answer though.
Give this method a try instead of your $img = $category->getImageUrl(); to $img = getCategoryImage($category);
function getCategoryImage($category) {
$categoryCollection = Mage::getModel('catalog/category')->setStoreId(Mage::app()->getStore()->getId())->getCollection()->addAttributeToSelect('image')->addIdFilter($category->getId());
foreach($categoryCollection as $category) {
return $category->getImageUrl();
}
}
(now defunct) Reference: http://www.magentocommerce.com/boards/viewthread/5026/P45/
I'm trying to retrieve products that carry same attribute. Specifically multiple select type. It seems the basic methods don't work. Selecting only the "name" attribute, I get all my products listed. When I try to filter "shop_by_color", it filters down, but not entirely. Not sure why it removes some and leaves others, even though they are the wrong ones. Any tips appreciated.
<?php
$model = Mage::getModel('catalog/product');
$collection = $model->getCollection();
$collection->addAttributeToSelect('name');
$collection->addAttributeToFilter('shop_by_color'); // multiple select attribute
$collection->addFieldToFilter(array(array('attribute'=>'shop_by_color','finset'=>array('Yellow, White'),
)));
$collection->load();
?>
<ul>
<?php foreach($collection as $product) : ?>
<li><?php echo $product->getName() ?></li>
<?php endforeach; ?>
</ul>
Hi I am not sure about your syntax I have never seen this sort of thing before.
<ul>
<?php foreach($collection as $product) : ?>
<li><a href="<?php echo $product->getProductUrl() ?>"><?php echo $product->getName()
?></a></li>
<?php endforeach; ?>
</ul>
Shouldn't it be...
<ul>
<?php foreach($collection as $product) { ?>
<li><a href="<?php echo $product->getProductUrl() ?>"><?php echo $product->getName()
?></a></li>
<?php } ?>
</ul>
DC
<?php
$_productCollection=$this->getLoadedProductCollection();
$_productCollection->clear()
->addAttributeToSelect('*')
->addAttributeToFilter('type_id', array('eq' => 'simple'))
->addAttributeToSort('name', 'ASC')
->addAttributeToSort('created_at', 'ASC')
->load();?>
on list page please use this type collection filter it's working fine.