문제

I want to get product id and also check that this product's category id and name. and also want to check that this current category id and selected product's category id equal or not...

도움이 되었습니까?

해결책

You can this code to get current product and its category

<?php 

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

$product = $objectManager->get('Magento\Framework\Registry')->registry('current_product');

echo $product->getId();
$categories = $product->getCategoryIds(); /*will return category ids array*/

foreach($categories as $category){

    $cat = $objectManager->create('Magento\Catalog\Model\Category')->load($category);

    echo $cat->getName();
    }

?>

다른 팁

Don't use Object Manager. Magento going to Deprecated objectManager in future. instead of this use inject method in constructor.

use Magento\Framework\Registry;    
use Magento\Catalog\Model\Category;
protected $category;
protected $registry;

 public function __construct(    
        Registry $registry, 
        Category $category
    ) {
        $this->registry = $category;
        $this->category = $category;
    }
$product = $this->registry->registry('current_product');
echo $product->getId();
$categories = $product->getCategoryIds(); 

foreach($categories as $category){
$cat = $this->category->load($category);

echo $cat->getName();
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 magento.stackexchange
scroll top