For a new import tool I need to category by path, this is an example of an path i have, for example:
main category/sub
main category/sub/sub
It always is the name, not the url or stuff. It is possible to get an category ID by this path?
I recently created something identical to this, basically mimicked the functionality from Mage_ImportExport_Model_Import_Entity_Product.
Usage
See all paths in system:
Mage::getModel('your_module/category_finder')->getAllPaths()
Search path, returns category id:
Mage::getModel('your_module/category_finder')->getIdFromPath('main category/sub/sub');
See the gist: https://gist.github.com/jzahedieh/6884204 or:
<?php
/**
* Functionality taken from Mage_ImportExport_Model_Import_Entity_Product
*/
class Your_Module_Model_Category_Finder
{
/**
* Categories text-path to ID hash.
*
* @var array
*/
protected $_categories = array();
/**
* Categories text-path to ID hash with roots checking.
*
* @var array
*/
protected $_categoriesWithRoots = array();
/**
* Populates the models properties with category information.
*/
public function __construct()
{
$this->_initCategories();
}
/**
* Finds a subcategory id from a path string
*
* @param $string
* @return bool
*/
public function getIdFromPath($string)
{
if (in_array($string, array_keys($this->_categories))) {
return $this->_categories[$string];
}
return false;
}
/**
* Returns all valid path strings
*
* @return array
*/
public function getAllPaths()
{
return array_keys($this->_categories);
}
/**
* Initialize categories text-path to ID hash.
*
* @return Mage_ImportExport_Model_Import_Entity_Product
*/
protected function _initCategories()
{
$collection = Mage::getResourceModel('catalog/category_collection')->addNameToResult();
/* @var $collection Mage_Catalog_Model_Resource_Eav_Mysql4_Category_Collection */
foreach ($collection as $category) {
$structure = explode('/', $category->getPath());
$pathSize = count($structure);
if ($pathSize > 1) {
$path = array();
for ($i = 1; $i < $pathSize; $i++) {
$path[] = $collection->getItemById($structure[$i])->getName();
}
$rootCategoryName = array_shift($path);
if (!isset($this->_categoriesWithRoots[$rootCategoryName])) {
$this->_categoriesWithRoots[$rootCategoryName] = array();
}
$index = implode('/', $path);
$this->_categoriesWithRoots[$rootCategoryName][$index] = $category->getId();
if ($pathSize > 2) {
$this->_categories[$index] = $category->getId();
}
}
}
return $this;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With