Magento2-通过ID获取类别URL


11

我正在尝试获取具有ID的任何给定类别的URL密钥。我有这个;

$categoryId = 3;
$_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$object_manager = $_objectManager->create('Magento\Catalog\Model\Category')->load($categoryId);
print_r($object_manager->getData());

这样就可以了(在print_r中有我需要的URL密钥),但是类别#3是顶级类别。每当我尝试任何子类别(例如ID 5)时,我都会得到一个空白数组。我只是迷失了语言,无法弄清楚。

在Magento 1.x中,我曾经这样做:Mage::getModel('catalog/category')->load($catID)->getUrl()并且有效。

TL; DR:此代码工作,更改ID为(正确)类别ID和更改getData()getUrl()了品类齐全的URL,或getName()为类别名称。

Answers:


28

为了获得类别URL,您需要使用如下\Magento\Catalog\Model\Category函数getUrl()

$category->getUrl()

另外,您可以通过以下方式获取网址 CategoryRepositoryInterface

nameSpace ['Your_nameSpace'] 
use Magento\Catalog\Api\CategoryRepositoryInterface;
class ['Your_Class_name']
    protected $_storeManager;
    protected $categoryRepository;
    public function __construct(
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Catalog\Model\CategoryRepository $categoryRepository,
    ) {
        .........
        $this->_storeManager = $storeManager;
        $this->categoryRepository = $categoryRepository;
    }

     public  function getCategory()
    {
            $category = $this->categoryRepository->get($categoryId, $this->_storeManager->getStore()->getId());

        return $category->getUrl();
    }
} 

谢谢:)将getData更改为getUrl是正确的选择。
Alex Timmer

工作正常,Up投票给您
Pushpendra Singh

好的答案,非常有帮助。+1
Shoaib Munir

12

始终尝试使用存储库。您需要注入以下方式:

/ **
 * @var \ Magento \ Catalog \ Helper \ Category
 * /
受保护的$ categoryHelper;

/ **
 * @var \ Magento \ Catalog \ Model \ CategoryRepository
 * /
受保护的$ categoryRepository;


公共功能__construct(
    \ Magento \ Catalog \ Helper \ Category $ categoryHelper,
    \ Magento \ Catalog \ Model \ CategoryRepository $ categoryRepository,

){
    $ this-> categoryHelper = $ categoryHelper;
    $ this-> categoryRepository = $ categoryRepository;
}

对于类别网址

$ categoryId = 3;
$ categoryObj = $ this-> categoryRepository-> get($ categoryId);
echo $ this-> categoryHelper-> getCategoryUrl($ categoryObj);

太棒了,谢谢你。我试图使用CategoryModel遍历ID,该ID通过迭代重新加载相同的数据。一头挠头后你救了我!
domdambrogia

6

您可以尝试以下代码。

$categoryId = 5;
$_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$object_manager = $_objectManager->create('Magento\Catalog\Model\Category')->load($categoryId);
echo "<pre>";
print_r($object_manager->getData());

使用类别ID之前,请先确认admin中存在类别ID,否则它将返回一个空数组。

如果您有任何疑问,请告诉我。


嗯,那是我在OP中编写的确切代码。但是您是正确的,我尝试了一些我认为已经存在但没有的ID。
Alex Timmer

1

我发现,当我需要来自不同域的类别URL(每个商店视图)时,必须在每个商店视图中创建一个新的Url对象。

use Magento\Catalog\Model\Category;
use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory;
use Magento\Framework\UrlFactory;

class CacheWarmer
{
    /** @var CollectionFactory */
    protected $categoryCollectionFactory;

    /** @var \Magento\Store\Model\StoreManagerInterface */
    protected $storeManager;

    /** @var UrlFactory */
    protected $urlFactory;

    public function __construct(
        CollectionFactory $categoryCollectionFactory,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        UrlFactory $urlFactory
    )
    {
        $this->categoryCollectionFactory = $categoryCollectionFactory;
        $this->storeManager = $storeManager;
        $this->urlFactory = $urlFactory;
    }

    /**
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function execute()
    {
        $stores = $this->storeManager->getStores();

        foreach ($stores as $store) {

            $this->storeManager->setCurrentStore($store);

            $collection = $this->categoryCollectionFactory->create();
            $collection->addUrlRewriteToResult();
            $collection->addIsActiveFilter();

            $urlCreator = $this->urlFactory->create();

            /** @var Category $category */
            foreach ($collection as $category) {

                $requestPath = $category->getRequestPath();
                if (!$requestPath) {
                    continue;
                }

                $url = $urlCreator->getDirectUrl($category->getRequestPath());

                $result = @file_get_contents($url);
            }
        }
    }
}

0

这在我的自定义块上正常工作(使用类别存储库和DI):

/**
 * Constructor
 */
public function __construct(
  \Magento\Catalog\Model\CategoryRepository $categoryRepository,
  // ...
) 
{
  $this->_categoryRepository = $categoryRepository;
  // ...
}


/**
 * Return the category object by its id.
 * 
 * @param categoryId (Integer)
 */
public function getCategory($categoryId)
{
  return $this->getCategoryRepository()->get($categoryId);
}


/**
 * Category repository object
 */
protected $_categoryRepository;

最后,在模板文件中,我只使用:

$this->getCategory(3)->getUrl()

0

@andrea请更新getCategory方法。要么运作良好。

/**
 * Return the category object by its id.
 * 
 * @param categoryId (Integer)
 */
public function getCategory($categoryId)
{
  return $this->_categoryRepository->get($categoryId);
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.