How to Get list of all Categories in Magento

How to Get list of all Categories in Magento

In this post we will show you how to get all main categories and all sub categories of magento store.
In this following code we can get all categories in

    and

  • html structure.
    Here are two recursive functions we are using

    get_child_categories() :: one outputs the categories as a DOM tree.
    render_categories_tree() :: returns a descriptive associative array.
    // include Mage.php for run file externaly / externally outside of magento 
    // if run externaly / externally outside of magento
    require_once("app/Mage.php");
    umask(0);
    Mage::app();
    // End externaly / externally outside of magento
    
    // for get child categories data ::
    function get_child_categories($get_category, $is_first_cat = false) {
    
            // If this is the first invocation, we just want to iterate through the top level categories, otherwise fetch the children
            $children_cat = $is_first_cat ? $get_category : $get_category->getChildren();
    
            // For each category, fetch its children recursively
            foreach ($children_cat as $child_val) {
                    $_categories[] = [ "name" => $child_val->getName(), "id" => $child_val->getId(), "children" => get_child_categories($child_val) ];
            }
    
            // Return our category result
            return $_categories;
    }
    
    // for render categories tree data ::
    function render_categories_tree($get_category, $is_first_cat = false) {
    
            $children_cat = $is_first_cat ? $get_category : $get_category->getChildren();
            echo "<ul>";
            // For echo of catagory ul and li structure.
            foreach ($children_cat as $child_val) 
    		{
                    echo "<li>"; 
    				echo $child_val->getName(); 
    				echo "</li>";
                    render_categories_tree($child_val);
            }
            echo "</ul>";
    		
    }
    
    
    // get categories 
    $store_categories = Mage::helper('catalog/category')->getStoreCategories();
    
    // associative array of all categories in function
    $categories = get_child_categories($store_categories, true);
    
    // Run this to echo of catagory ul and li structure.
    render_categories_tree($store_categories, true);

    OUTPUT

    Get Categories and Its Sub Categories
    Get Categories and Its Sub Categories

    Leave a Comment

    Your email address will not be published. Required fields are marked *

    3  +    =  8

    We accept paid advance and paid guest Posting on our Site : Contact US