为了在网站上显示促销产品系列,商店管理员将需要有关促销产品系列的数据。然而,获取集合并不是一件简单的任务,并且也没有太多文章来写这方面的解决方案。因此,在今天的帖子中,我将指导您如何在 Magento 2 中获得特价产品系列

3步获取特价产品系列

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

第 1 步:创建 OnSaleProduct 块 {}

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

<?php

namespace Example\Productslider\Block;
use Zend_Db_Expr;
/**
 * Class OnSaleProduct
 * @package Example\Productslider\Block
 */
class OnSaleProduct extends AbstractSlider
{
    /**
     * @inheritdoc
     */
    public function getProductCollection()
    {
        $visibleProducts = $this->_catalogProductVisibility->getVisibleInCatalogIds();
        $collection = $this->_productCollectionFactory->create()->setVisibility($visibleProducts);
        $collection = $this->_addProductAttributesAndPrices($collection)
            ->addAttributeToFilter(
                'special_from_date',
                ['date' => true, 'to' => $this->getEndOfDayDate()],
                'left'
            )->addAttributeToFilter(
                'special_to_date',
                ['or' => [0 => ['date' => true,
                                                   'from' => $this->getStartOfDayDate()],
                                             1 => ['is' => new Zend_Db_Expr(
                                                 'null'
                                             )],]],
                'left'
            )->addAttributeToSort(
                'news_from_date',
                'desc'
            )->addStoreFilter($this->getStoreId())->setPageSize(
                $this->getProductsCount()
            );
        return $collection;
    }
}

第2步:插入phtml文件{}

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

然后,请在 phtml 文件中插入以下代码。

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

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

最后,让我们刷新缓存并测试结果。