0

I am a beginner in Magento. This may be a simple question.

I have a header menu 'shop'. This link should redirect to a page that shows all parent categories. How can I do this? any help is really appreciated.

This is how the 'shop' page should looks like (Parent categories only).

This what I need

Thank you.

0

Please try this code.

$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();        


$categoryFactory = $objectManager->get('\Magento\Catalog\Model\CategoryFactory');
$categoryHelper = $objectManager->get('\Magento\Catalog\Helper\Category');
$categoryRepository = $objectManager->get('\Magento\Catalog\Model\CategoryRepository');

$categoryId = 3; // YOUR CATEGORY ID
$category = $categoryFactory->create()->load($categoryId);

//var_dump($category->getData());

$parentCategories = $category->getParentCategories();
$childrenCategories = $category->getChildrenCategories();
$subcats = $childrenCategories->getData();

foreach ($childrenCategories as $cat) {
    echo $cat->getName();
    echo "<br>";
}

and then use it in your .phtml file. Hope it works!

|improve this answer|||||
0

You can try this code:

first you create a category source file inside Model:

Note: Here root categories are excluded.

path: Vendor\ModuleName\Model\Source\Categories.php

Categories.php

<?php

namespace Vendor\ModuleName\Model\Source;

class Categories implements \Magento\Framework\Option\ArrayInterface {

    protected $_categoryFactory;
    protected $_categoryCollectionFactory;

    public function __construct(
       \Magento\Catalog\Model\CategoryFactory $categoryFactory,
       \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory
    ) {
        $this->_categoryFactory = $categoryFactory;
        $this->_categoryCollectionFactory = $categoryCollectionFactory;
    }

    public function getCategoryCollection($isActive = true, $level = false, $sortBy = false, $pageSize = false, $excludeLevel = false) {
        $collection = $this->_categoryCollectionFactory->create();
        $collection->addAttributeToSelect('*');

        // select only active categories
        if ($isActive) {
            $collection->addIsActiveFilter();
        }

        // select categories of certain level
        if ($level) {
            $collection->addLevelFilter($level);
        }

        // sort categories by some value
        if ($sortBy) {
            $collection->addOrderField($sortBy);
        }

        // select certain number of categories
        if ($pageSize) {
            $collection->setPageSize($pageSize);
        }

        $this->excludeRootCategories($collection, $excludeLevel);

        return $collection;
    }

    public function toOptionArray() {
        return $arr = $this->_toArray();
    }

    private function _toArray() {
        $categories = $this->getCategoryCollection(false, false, false, false);

        $catagoryList = array();
        foreach ($categories as $category) {
            $catagoryList[] = ['label' => __($this->_getParentName($category->getPath()) . $category->getName()), 'value' => $category->getEntityId()];
        }

        return $catagoryList;
    }

    private function _getParentName($path = '') {
        $parentName = '';
        $rootCats = array(1, 2);

        $catTree = explode("/", $path);
        // Deleting category itself
        array_pop($catTree);

        if ($catTree && (count($catTree) > count($rootCats))) {
            foreach ($catTree as $catId) {
                if (!in_array($catId, $rootCats)) {
                    $category = $this->_categoryFactory->create()->load($catId);
                    $categoryName = $category->getName();
                    $parentName .= $categoryName . ' -> ';
                }
            }
        }

        return $parentName;
    }

    public function excludeRootCategories($collection, $excludeLevel) {
        $collection->addFieldToFilter('level', ['gteq' => $excludeLevel]);
        return $this;
    }

    public function getCategoriesOptionsArray() {
        $categories = $this->getCategoryCollection(true, 2, false, false, 2);

        $catagoryList = array();
        foreach ($categories as $category) {
            $catagoryList[] = ['label' => __($this->_getParentName($category->getPath()) . $category->getName()), 'value' => $category->getEntityId()];
        }

        return $catagoryList;
    }

}

Now you need to call the categories model class in your block file:

.........
protected $_categoriesSource;
.........

public function __construct(
        ..........
        \Vendor\ModuleNAme\Model\Source\Categories $categoriesSource, 
        ..........
) {
    ......
    $this->_categoriesSource = $categoriesSource;
    ......
}

public function getParentCategoryOptions() {
    return $this->_categoriesSource->getCategoriesOptionsArray();
}

finally, you can get the lists of all parent categories in phtml file:

$categoryOptions = $block->getParentCategoryOptions();
echo '<pre>';
print_r(categoryOptions);

Hope, this solution will help you!

|improve this answer|||||

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.