Stack Exchange
Not able to get proper parent category for specific child category
I have "ABC" as a parent category and "XYZ" as a child category. While opening the "XYZ" child category, on that page breadcrumb is appeared as below
Home > XYZ (child category) > ABC (parent category)
instead of
Home > ABC (parent category) > XYZ (child category)
I have used below code to get category breadcrumbs:
if ($category->getParentCategories()) 
{
    foreach ($category->getParentCategories() as $parent) {
        $breadcrumbs[] = [
            'label' => $parent->getName()
        ];
    }
}


Have you checked your in Magento Admin? If not got to admin->catalog->categories and rearrange categories as per needed

Yes, Initially I had do this steps in admin, but could not got the solution.

You need to use the categories IDs stored in the current categorie's path in store and process it in reverse order like this:
$pathInStore = $category->getPathInStore();
$pathIds = array_reverse(explode(',', $pathInStore));
$categories = $category->getParentCategories();

// add category path breadcrumb
foreach ($pathIds as $categoryId) {
    if (isset($categories[$categoryId]) && $categories[$categoryId]->getName()) {
       $breadcrumbs[] = $categories[$categoryId]->getName();
   }
}


While checking the category attribute "path_in_store" entry in database and found that their is no any entries for all the categories in database.

<?php

namespace Your-Vendor\Your-Module\Block;

use Magento\Framework\View\Element\Template;
use Magento\Backend\Block\Template\Context;
use Magento\Catalog\Model\CategoryFactory;
use Magento\Framework\Registry;

class Category extends Template{

    protected $categoryFactory;
    protected $registry;
    protected $category;

    public function __construct(
        Context $context,
        CategoryFactory $categoryFactory,
        Registry $registry,
        array $data = []
    )
    {
        $this->categoryFactory = $categoryFactory;
        $this->registry = $registry;
        parent::__construct($context, $data);
    }

    public function getCurrentProduct()
    {
        return $this->registry->registry('current_product');
    }

    public function getCategory($categoryId)
    {
        $this->category = $this->categoryFactory->create();
        $this->category->load($categoryId);
        return $this->category;
    }
}

?>


<?php
$product = $this->getCurrentProduct();

$categoryIds = $product->getCategoryIds();
foreach ($categoryIds as $categoryId){
    $category = $this->getCategory($categoryId);
    $parentCategories = $category->getparent_id();
    echo $parentCategories. '<br />';
}
?>

