1

I am displaying all Custom Categories & its sub-categories in Json format with help of below code....

Note : These Categories & its sub-categories are created using custom module

<?php

require_once('app/Mage.php');
Mage::app();

$cat_model = Mage::getModel('ultimate_mars/category');
$_categories = $cat_model->getTreeModel()->getCollection()->addFieldToFilter("entity_id", array('gt' => 1));

$category = array();
foreach($_categories as $_category)
{
    $category[] = array("name" => $_category->getCategoryname(), "id" => $_category->getEntityId());
}

echo json_encode($category);

Result :

enter image description here

What i need :

If i pass particular category id [say Tshirts id] in Url, than i need to display only its sub-categories [ say Men & Women ] in JSON format....

app/code/local/Ultimate/Mars/Model - Category.php

<?php

    class Ultimate_Mars_Model_Category extends Mage_Core_Model_Abstract
    {

        const ENTITY    = 'ultimate_mars_category';
        const CACHE_TAG = 'ultimate_mars_category';

        protected $_eventPrefix = 'ultimate_mars_category';

        protected $_eventObject = 'category';

        public function _construct()
        {
            parent::_construct();
            $this->_init('ultimate_mars/category');
        }

        public function getSelectedProductsCollection()
        {
            if (!$this->hasData('_product_collection')) {
                if (!$this->getId()) {
                    return new Varien_Data_Collection();
                } else {
                    $collection = Mage::getResourceModel('ultimate_mars/product_collection')
                            ->addFieldToFilter('category_id', $this->getId());
                    $this->setData('_product_collection', $collection);
                }
            }
            return $this->getData('_product_collection');
        }

        public function getTreeModel()
        {
            return Mage::getResourceModel('ultimate_mars/category_tree');
        }

        public function getTreeModelInstance()
        {
            if (is_null($this->_treeModel)) {
                $this->_treeModel = Mage::getResourceSingleton('ultimate_mars/category_tree');
            }
            return $this->_treeModel;
        }

        public function getParentCategory()
        {
            if (!$this->hasData('parent_category')) {
                $this->setData(
                    'parent_category',
                    Mage::getModel('ultimate_mars/category')->load($this->getParentId())
                );
            }
            return $this->_getData('parent_category');
        }

        public function getParentId()
        {
            $parentIds = $this->getParentIds();
            return intval(array_pop($parentIds));
        }


        public function getParentIds()
        {
            return array_diff($this->getPathIds(), array($this->getId()));
        }


        public function getAllChildren($asArray = false)
        {
            $children = $this->getResource()->getAllChildren($this);
            if ($asArray) {
                return $children;
            } else {
                return implode(',', $children);
            }
        }

        public function getChildCategorys()
        {
            return implode(',', $this->getResource()->getChildren($this, false));
        }


        public function checkId($id)
        {
            return $this->_getResource()->checkId($id);
        }


        public function getPathIds()
        {
            $ids = $this->getData('path_ids');
            if (is_null($ids)) {
                $ids = explode('/', $this->getPath());
                $this->setData('path_ids', $ids);
            }
            return $ids;
        }

        public function getLevel()
        {
            if (!$this->hasLevel()) {
                return count(explode('/', $this->getPath())) - 1;
            }
            return $this->getData('level');
        }


        public function verifyIds(array $ids)
        {
            return $this->getResource()->verifyIds($ids);
        }

        public function hasChildren()
        {
            return $this->_getResource()->getChildrenAmount($this) > 0;
        }

        public function getCategorys($parent, $recursionLevel = 0, $sorted=false, $asCollection=false, $toLoad=true)
        {
            return $this->getResource()->getCategorys($parent, $recursionLevel, $sorted, $asCollection, $toLoad);
        }


        public function getParentCategorys()
        {
            return $this->getResource()->getParentCategorys($this);
        }


        public function getChildrenCategorys()
        {
            return $this->getResource()->getChildrenCategorys($this);
        }


        public function getStatusPath()
        {
            $parents = $this->getParentCategorys();
            $rootId = Mage::helper('ultimate_mars/category')->getRootCategoryId();
            foreach ($parents as $parent) {
                if ($parent->getId() == $rootId) {
                    continue;
                }
                if (!$parent->getStatus()) {
                    return false;
                }
            }
            return $this->getStatus();
        }        
    }

Here is link to Download module : link

1
+100

use below code to get sub category of category tshirt

<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once('app/Mage.php');
Mage::app();


$cat_model = Mage::getModel('ultimate_mars/category');
$reqCat = (int)$_REQUEST['category_id'];
if ($reqCat > 0) {



    $_cate = $cat_model->getTreeModel()->getCollection()->addFilter("parent_id", $reqCat);



} else {
    $_cate = $cat_model->getTreeModel()->getCollection()->addFieldToFilter("entity_id", array('gt' => 1));
}


$category = array();
foreach ($_cate as $_category) {
    $category[] = array("name" => $_category->getCategoryname(), "id" => $_category->getEntityId());
}

echo json_encode($category);
2
$parentCatId = 1;// pass your required category id here

$category = Mage::getModel('catalog/category')
        load($parentCatId)
        ;


$subcats = $category->getChildren();


 $subcat=array();
foreach(explode(',',$subcats) as $subCatid)
{
  $_category = Mage::getModel('catalog/category')->load($subCatid);
  if($_category->getIsActive())
  {
     $image = $_category->getImageUrl();

    $subcat[]=array(
           "id"=>$_category->getId(), 
           "url"=>($_category->getURL())  ? $_category->getURL() : "", 
            "name"=>($_category->getName())  ? $_category->getName() : "",
            "meta_title"=>($_category->getMetaTitle())  ? $_category->getMetaTitle(): "", 
            "meta_keywords"=>($_category->getMetaKeywords())  ? $_category->getMetaKeywords(): "",
            "meta_description"=>($_category->getMetaDescription())  ? $_category->getMetaDescription(): "",
            "image_url"=>($image)  ? $image: "",
    );

  }
  • Thanks, your code is for magento default categories , i am using custom module to create categories, please check code i posted in question.... – Baby in Magento Nov 14 '18 at 7:30
2

Can you replace below code

$_categories = $cat_model->getTreeModel()->getCollection()->addFieldToFilter("entity_id", array('gt' => 1));

with

$_categories = $cat_model->getTreeModel()->getCollection()->addFieldToFilter("entity_id", array('eq' => 2));

I have not checked this but it should help you.

  • Thanks for answer, its displaying result [{"name":"Tshirts","id":"2"}] means when we pass category_id : 2 in url , its displaying only category_id 2 , but what i need is to when we pass category_id : 2 in url , it should display only its subcategories , i.e Men & Women..... – Baby in Magento Nov 15 '18 at 7:16
1

Try this code working fine for me

<?php require_once('app/Mage.php');
Mage::app();

$categryId = 2; /* Your requested category ID */ 
$yourCategory = Mage::getModel('ultimate_mars/category')->load($categryId);

$childLevel = (int)$yourCategory->getData("categorylevel") + 1;
/* Getting subcategory of requested category id */
$cat_model = Mage::getModel('ultimate_mars/category');
$_categories = $cat_model->getTreeModel()->getCollection()->addFieldToFilter("parent_id",$yourCategory->getId())->addFieldToFilter("categorylevel",$childLevel);

$category = array();
foreach($_categories as $_category)
{
    $category[] = array("name" => $_category->getCategoryname(), "id" => $_category->getEntityId());
}

echo json_encode($category);
  • Hi, Thanks for your help, i tried your code, i got result as : [{"name":"Women","id":"4"}] means i have 3 subcategories for category id- 2 , in that only 1 subcategory displayed : [{"name":"Women","id":"4"}], but i already got answer for this question from other answer by user jigs parmar.... – Baby in Magento Nov 16 '18 at 5:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.