Вставай - продавай товар в Magento 2


Я пытаюсь повысить продажи продукта в Magento 2 с помощью ObjectManager. Текущий идентификатор и название продукта возвращаются хорошо, но возврат продукта с повышением продаж пуст.

<?php 
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $product = $objectManager->get('Magento\Framework\Registry')->registry('current_product');//get current product
    echo $product->getId();
    echo $product->getName();
    //echo $currentProduct->getSku();
if ($currentProduct = $product->getCurrentProduct()) {
    $upSellProducts = $currentProduct->getUpSellProducts();
    print_r($upSellProducts);

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

enter image description here

Author: Prince Patel, 2017-06-08

2 answers

Заводским Методом:

protected $_registry;

public function __construct(
    ...
    \Magento\Framework\Registry $registry,
    ...
) {
    $this->_registry = $registry;
}

public function getCurrentProduct()
{
    return $this->_registry->registry('current_product');
}

public function getUpsellProducts()
{
    $currentProduct = $this->getCurrentProduct();
    $upsellProducts = $currentProduct->getUpSellProducts();

    return $upsellProducts;
}

С помощью диспетчера объектов:

<?php 
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$currentProduct = $objectManager->get('Magento\Framework\Registry')->registry('current_product');//get current product

if ($currentProduct) {

    $upsellProducts = $currentProduct->getUpSellProducts();

    if (!empty($upsellProducts)) {
        echo '<h3>UpSell Products</h3>';
        foreach ($upsellProducts as $upsellProduct) {
            echo $id = $upSellProduct->getSku();
        }
    }
}

Примечание: С помощью этого кода вы не сможете получить полную модель продукта. Для этого вам необходимо загрузить модель продукта по идентификатору продукта upsell.

 1
Author: Prince Patel, 2018-02-22 06:08:14
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->get('Magento\Framework\Registry')->registry('current_product');//get current product
echo $product->getId();
echo $product->getName();
//echo $currentProduct->getSku();
if ($currentProduct = $product) {
    $upSellProducts = $currentProduct->getUpSellProducts();
    //print_r($upSellProducts);

    if (!empty($upSellProducts)) {
        echo '<h3>UpSell Products</h3>';
        foreach ($upSellProducts as $upSellProduct) {
            echo $upSellProduct->getSku() . '<br />';        
        }
    }
}
 0
Author: nikhil sharma, 2019-05-08 13:55:34