سؤال

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