在 MAGENTO 2 中展示畅销产品的分步过程

请按照以下步骤了解如何在您的 Magento 2 商店中展示畅销产品。

首先,我们需要获得畅销产品集合。

为此,我们需要MageDelight/Productslider/Block/文件夹中创建一个名为BestSellerProducts.php的块并粘贴以下代码:

 

<?php

namespace MageDelight\Productslider\Block;

use Magento\Catalog\Block\Product\Context;

use Magento\Catalog\Model\Product\Visibility;

use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;

use Magento\Framework\App\Http\Context as HttpContext;

use Magento\Framework\Stdlib\DateTime\DateTime;

use Magento\Sales\Model\ResourceModel\Report\Bestsellers\CollectionFactory as BestSellersCollectionFactory;

use MageDelight\Productslider\Helper\Data;

/**

 * Class BestSellerProducts

 * @package MageDelight\Productslider\Block

 */

class BestSellerProducts extends AbstractSlider

{

    /**

     * @var BestSellersCollectionFactory

     */

    protected $_bestSellersCollectionFactory;

    /**

     * BestSellerProducts constructor.

     * @param Context $context

     * @param CollectionFactory $productCollectionFactory

     * @param Visibility $catalogProductVisibility

     * @param DateTime $dateTime

     * @param Data $helperData

     * @param HttpContext $httpContext

     * @param BestSellersCollectionFactory $bestSellersCollectionFactory

     * @param array $data

     */

    public function __construct(

        Context $context,

        CollectionFactory $productCollectionFactory,

        Visibility $catalogProductVisibility,

        DateTime $dateTime,

        Data $helperData,

        HttpContext $httpContext,

        BestSellersCollectionFactory $bestSellersCollectionFactory,

        array $data = []

    ) {

        $this->_bestSellersCollectionFactory = $bestSellersCollectionFactory;

        parent::__construct($context, $productCollectionFactory, $catalogProductVisibility, $dateTime, $helperData, $httpContext, $data);

    }

    /**

     * get collection of best-seller products

     * @return mixed

     */

    public function getProductCollection()

    {

        $productIds = [];

        $bestSellers = $this->_bestSellersCollectionFactory->create()

            ->setPeriod('month');

        foreach ($bestSellers as $product) {

            $productIds[] = $product->getProductId();

        }

        $collection = $this->_productCollectionFactory->create()->addIdFilter($productIds);

        $collection->addMinimalPrice()

            ->addFinalPrice()

            ->addTaxPercents()

            ->addAttributeToSelect('*')

            ->addStoreFilter($this->getStoreId())->setPageSize($this->getProductsCount());

        return $collection;

    }

}

之后,我们需要将畅销产品集合插入块中的 phtml 文件中。

为此,在MageDelight/HelloWorld/view/frontend/templates/文件夹中创建一个list.phtml文件并粘贴以下代码:

getProductCollection();

foreach ($collection as $_product) {

    echo $product->getName() . ' - ' . $product->getProductUrl() . '
'; }