Question

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...

Était-ce utile?

La solution

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();
    }

?>

Autres conseils

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();
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à magento.stackexchange
scroll top