Magento 2:获取相关的UpSell和CrossSell产品

本文说明了如何在Magento 2中获得相关产品,追加销售产品和交叉销售产品。

以下是我的自定义模块(Chapagain_HelloWorld)的块类。我在模块的模块类的构造函数中注入了\ Magento \ Framework \ Registry类的对象。

app / code / Chapagain / HelloWorld / Block / HelloWorld.php

<?php
namespace Chapagain\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 getCurrentProduct()
    {        
        return $this->_registry->registry('current_product');
    }    
    
}
?>

在模板(.phtml)文件中打印相关的加售和交叉销售产品

$currentProduct = $block->getCurrentProduct();
 
$relatedProducts = $currentProduct->getRelatedProducts();
$upSellProducts = $currentProduct->getUpSellProducts();
$crossSellProducts = $currentProduct->getCrossSellProducts();
    
if (!empty($relatedProducts)) {
    echo 'Related Products <br />';    
    foreach ($relatedProducts as $relatedProduct) {
        echo $relatedProduct->getSku() . '<br />';        
    }
}    
    
if (!empty($upSellProducts)) {
    echo 'UpSell Products <br />';
    foreach ($upSellProducts as $upSellProduct) {
        echo $upSellProduct->getSku() . '<br />';        
    }
}
    
if (!empty($crossSellProducts)) {
    echo 'CrossSell Products <br />';
    foreach ($crossSellProducts as $crossSellProduct) {
        echo $crossSellProduct->getSku() . '<br />';        
    }
}

使用对象管理器

$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();        
 
$appState = $objectManager->get('\Magento\Framework\App\State');
$appState->setAreaCode('frontend');
 
$registry = $objectManager->get('\Magento\Framework\Registry');
 
$currentProduct = $registry->registry('current_product');
 
$relatedProducts = $currentProduct->getRelatedProducts();
$upSellProducts = $currentProduct->getUpSellProducts();
$crossSellProducts = $currentProduct->getCrossSellProducts();

有关更多信息,请参见:

– MAGENTO_ROOT / vendor / magento / module-catalog / Model / Product.php

希望这可以帮助。谢谢。

相关文章

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