Upgrading an M1 site that uses the following function to output a link to a custom product attribute collection. Can someone help me with the proper way to do this in M2? Thanks!

$cats = $_product->getCategoryIds();


 * @param $cats
 * @return string
function addSeriesLinkToMsg($cats)
    if (in_array(SERIES_CAT, $cats))
        //Loop through all categories and find the furthest down
        $series_cat = Mage::getModel('catalog/category')->load(SERIES_CAT);
        foreach ($cats as $cat)
            $my_cat = Mage::getModel('catalog/category')->load($cat);

            if (stristr($my_cat->getPath(), "/" . SERIES_CAT . "/") && $my_cat->getLevel() > $series_cat->getLevel())
                $series_cat = $my_cat;


        //Only display the message if the series category isn't the root
        if ($series_cat->getId() != SERIES_CAT)
            return "Series: <a href=\"" . $series_cat->getUrl() . "\">" . $series_cat->getName() . "</a>";
    return '';

1 Answer 1


you can use below code:

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

// Here one more loop with same code you can require if same child levels which was in M1

foreach($cats as $cat){ $my_cat = $this->categoryFactory->create()->load($cat); }

NOTE: Use Factory Type as I mentioned above it will create new object every time like getModel() in M1.

See below link for more load category by ID useinng DI and Object Manager

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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