Get up-sell product in Magento 2
-
09-10-2020 - |
Frage
I am trying to get up-sell product in Magento 2 via objectManager. Current product id and name is returning well but up-sell product return empty.
<?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 />';
}
}
}
?>
Lösung
By Factory Method:
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;
}
By ObjectManager:
<?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();
}
}
}
Note: With this code, you cannot get full model of product. For that, you need to load product model by upsell product Id.
Andere Tipps
$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 />';
}
}
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit magento.stackexchange