在 Magento 商店中展示特色产品是交叉销售和追加销售产品的有效方式。

然而,为了展示特色产品,商店管理员需要获取特色产品集合,这对于新开发人员或非技术商店管理员来说可能并不容易。因此,在今天的文章中,我将向您展示在 Magento 2 中获取特色产品集合的三个步骤。

在 Magento 2 中获取特色产品系列的 3 个步骤

  • 第 1 步:创建特色产品块
  • 第 2 步:插入phtml文件
  • 第 3 步:刷新缓存和测试结果

第 1 步:创建特色产品块

要获取特征产品集合,首先需要创建一个FeaturedProducts块。为此,请按照路径Example/Productslider/Block/FeaturedProducts.php添加以下代码:

<?php
namespace Example\Productslider\Block;
/**
 * Class FeaturedProducts
 * @package Example\Productslider\Block
 */
class FeaturedProducts extends AbstractSlider
{
    /**
     * get collection of feature products
     * @return mixed
     */
    public function getProductCollection()
    {
        $visibleProducts = $this->_catalogProductVisibility->getVisibleInCatalogIds();
        $collection = $this->_productCollectionFactory->create()->setVisibility($visibleProducts);
        $collection->addMinimalPrice()
            ->addFinalPrice()
            ->addTaxPercents()
            ->addAttributeToSelect('*')
            ->addStoreFilter($this->getStoreId())
            ->setPageSize($this->getProductsCount())
            ->addAttributeToFilter('is_featured', '1');
        return $collection;
    }
}

步骤2:插入phtml文件

在块中拥有集合后,现在您可以按照此代码片段从块中获取产品集合Example/HelloWorld/view/frontend/templates/list.phtml

接下来,请将以下代码插入phtml file

<?php
$collection = $block->getProductCollection();
foreach ($collection as $_product) {
    echo $product->getName() . ' - ' . $product->getProductUrl() . '<br />';
}

第 3 步:刷新缓存和测试结果

最后,为了完成获取特色产品集合,让我们刷新缓存并测试结果。