Magento 2 获得相关,追加销售和交叉销售产品

Magento 2中的相关,追加销售和交叉销售产品是您可以用于营销活动以在线推广的产品类型。对于观看产品,相关产品是具有类似功能的项目,并且向上销售产品是高于该产品的版本。怎么样 crosssell产品?它们是完美使用的伴随产品。在本主题中,您可以通过代码脚本了解如何获取所有这些内容。

概观

  • 第1步:声明 Mageplaza_HelloWorld
  • 第2步:获取相关产品
  • 第3步:获取销售产品
  • 第4步:获取crosssell产品

第1步:在Mageplaza_HelloWorldBlock中声明

您将使用模块的块类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 getCurrentProduct()
    {        
        return $this->_registry->registry('current_product');
    }    
    
}
?>

在步骤2中,您将申请该类Object Manager的自定义HelloWorld。通过这种方式,允许调用当前产品信息,然后逐一获得当前产品的相关,追加销售和交叉销售产品。

$myBlock = \Magento\Framework\App\ObjectManager::getInstance()->get('Mageplaza\HelloWorld\Block\HelloWorld');
 
$currentProduct = $myBlock->getCurrentProduct();
 
if ($currentProduct = $myBlock->getCurrentProduct()) {
    $relatedProducts = $currentProduct->getRelatedProducts();
    
    if (!empty($relatedProducts)) {
        echo 'Related Products <br />';    
        foreach ($relatedProducts as $relatedProduct) {
            echo $relatedProduct->getSku() . '<br />';  
            echo $relatedProduct->getName(); //get name
            echo $relatedProduct->getPrice(); //get price
            echo $relatedProduct->getData(); //Show all attributes      
        }
    }    
   
}

第3步:获取销售产品

$myBlock = \Magento\Framework\App\ObjectManager::getInstance()->get('Mageplaza\HelloWorld\Block\HelloWorld');
$currentProduct = $myBlock->getCurrentProduct();
 
if ($currentProduct = $myBlock->getCurrentProduct()) {
    $upSellProducts = $currentProduct->getUpSellProducts();

    if (!empty($upSellProducts)) {
        echo '<h3>UpSell Products</h3>';
        foreach ($upSellProducts as $upSellProduct) {
            echo $upSellProduct->getSku() . '<br />';        
        }
    }
    
   
}

第4步:获取crosssell产品

$myBlock = \Magento\Framework\App\ObjectManager::getInstance()->get('Mageplaza\HelloWorld\Block\HelloWorld');
$currentProduct = $myBlock->getCurrentProduct();
 
if ($currentProduct = $myBlock->getCurrentProduct()) {
    $crossSellProducts = $currentProduct->getCrossSellProducts();

    if (!empty($crossSellProduct)) {
        echo 'CrossSell Products <br />';
        foreach ($crossSellProducts as $crossSellProduct) {
            echo $crossSellProduct->getSku() . '<br />';        
        }
    }
    
   
}

如果您对文章或任何问题有任何疑问,请使用下面的评论部分!

相关文章

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