質問

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