表内容
- 在Magento 2中获取产品的概述
- 第1步:在Mageplaza_HelloWorld Block中声明
- 第2步:在phtml文件中显示产品集合
在Magento 2中获取集合意味着在运行命令时显示商店中的项目。使用本主题中的代码段,您可以根据需要请求特定数量的产品。我们现在开始在您的Magento 2商店中调用该产品!
在Magento 2中获取产品的概述
- 第1步:在
Mageplaza_HelloWorld
Block中声明 - 第2步:在
phtml
文件中显示产品集合
第1步:在Mageplaza_HelloWorld
Block中声明
您将使用模块的块类Mageplaza_HelloWorld
,然后可能\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory
在模块的块类的构造函数中注入对象。
app/code/Mageplaza/HelloWorld/Block/HelloWorld.php
<?php
namespace Mageplaza\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{
protected $_productCollectionFactory;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
array $data = []
)
{
$this->_productCollectionFactory = $productCollectionFactory;
parent::__construct($context, $data);
}
public function getProductCollection()
{
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->setPageSize(3); // fetching only 3 products
return $collection;
}
}
?>
您可以请求产品集合的编号,即有限或无限的编号。
第2步:在phtml
文件中显示产品集合
phtml
使用以下代码打印产品集合:
$productCollection = $block->getProductCollection();
foreach ($productCollection as $product) {
print_r($product->getData());
echo "<br>";
}
如果您对文章或任何问题有任何疑问,请使用下面的评论部分!