Warning: Cannot modify header information - headers already sent by (output started at /www/wwwroot/sbboke.com/wp-content/plugins/wordpress-seo/src/integrations/front-end-integration.php:409) in /www/wwwroot/sbboke.com/wp-content/themes/pacify/content-single.php on line 5

Magento 2中的当前产品和当前类别

如果您想知道如何获取/打印当前产品的信息甚至是当前类别,那么主题就是您需要找到的所有内容。本主题建议采取两个步骤,请获取并执行您需要的任何操作。

概观

  • 第1步:声明 Mageplaza_HelloWorld
  • 第2步:在模板phtml文件中打印出当前产品
  • 第3步:在模板phtml文件中打印出当前类别

第1步:在Mageplaza_HelloWorld中声明

您将使用模块Mageplaza_HelloWorld的块类,然后可能\Magento\Framework\Registry在模块的块类的构造函数中注入对象。

app/code/Mageplaza/HelloWorld/Block/HelloWorld.php

<?php
namespace Mageplaza\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{
        protected $_registry;
        
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,        
        \Magento\Framework\Registry $registry,
        array $data = []
    )
    {        
        $this->_registry = $registry;
        parent::__construct($context, $data);
    }
    
    public function _prepareLayout()
    {
        return parent::_prepareLayout();
    }
    
    public function getCurrentCategory()
    {        
        return $this->_registry->registry('current_category');
    }
    
    public function getCurrentProduct()
    {        
        return $this->_registry->registry('current_product');
    }    
    
}
?>

第2步:获取模板phtml文件中的当前产品

当前产品包括以下信息:名称,sku,最终价格,URL和相关类别ID。当前类别附带信息名称和网址。现在请运行命令打印出当前产品和当前类别。

$myBlock = \Magento\Framework\App\ObjectManager::getInstance()->get('Mageplaza\HelloWorld\Block\HelloWorld');
 

// print current product data
if ($currentProduct = $myBlock->getCurrentProduct()) {
    echo $currentProduct->getName() . '<br />';
    echo $currentProduct->getSku() . '<br />';
    echo $currentProduct->getFinalPrice() . '<br />';
    echo $currentProduct->getProductUrl() . '<br />';
    print_r ($currentProduct->getCategoryIds()) . '<br />';    
}

第3步:获取模板phtml文件中的当前类别

$myBlock = \Magento\Framework\App\ObjectManager::getInstance()->get('Mageplaza\HelloWorld\Block\HelloWorld');
 
// print current category data
if ($currentCategory = $myBlock->getCurrentCategory()) {    
    echo $currentCategory->getName() . '<br />';
    echo $currentCategory->getUrl() . '<br />';        
}

这是获取Magento 2当前产品和当前类别的指南。如果您对文章或任何问题有任何疑问,请使用下面的评论部分!

相关文章

0 0 投票数
文章评分
订阅评论
提醒
0 评论
内联反馈
查看所有评论