Actually, I want to get a current category, subcategory name, and URL.

Below code is not useful...

<?php
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Mage_Tempjs',
    __DIR__
);

I found this code and it is working fine for some products but for some products it's not working...

<?php

    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $category = $objectManager->get('Magento\Framework\Registry')->registry('current_category');
    $catName = $category->getName(); // to get the category name
    $catUrl = $category->getUrl(); // to get the category Url
  • Can you update your full code? – Sukumar Gorai Sep 14 at 11:59
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
      $category = $objectManager->get('Magento\Framework\Registry')->registry('current_category');
$category->getId();
$category->getAllChildern();
  • why registry is working for some products but for some products its not working – hitesh balpande Sep 14 at 14:49

Following way you get Subcategories by category Id.

public function __construct(
    \Magento\Catalog\Model\CategoryFactory $categoryFactory
) {
    $this->categoryFactory = $categoryFactory;
}

$categoryId = 4;
$category = $this->categoryFactory->create()->load($categoryId);

$subcategories = $category->getChildrenCategories();
foreach ($subcategories as $subcategorie) {
    echo $subcategorie->getId();
    echo $subcategorie->getName();
}

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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