0

I am facing issue in Magento 2.1.7

If special price date has expired for any products , i want to remove special price and special price to date and special price from date form products, by using crons.

i have tried everything but couldn't find a way to resolve it. Any suggestion appreciated.

Thanks in advance.

1

Try following way


<?php
namespace SR\StackExchange\Cron;

use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory as ProductCollectionFactory;
use Magento\Framework\Stdlib\DateTime\DateTime;
use Magento\Catalog\Api\ProductRepositoryInterface;

class ProcessSpecialProducts
{
    /**
     * @var ProductCollectionFactory
     */
    private $productCollectionFactory;

    /**
     * @var DateTime
     */
    private $date;

    /**
     * @var ProductRepositoryInterface
     */
    private $productRepository;

    /**
     * ProcessSpecialProducts constructor.
     *
     * @param ProductCollectionFactory $productCollectionFactory
     * @param ProductRepositoryInterface $productRepository
     * @param DateTime $date
     */
    public function __construct(
        ProductCollectionFactory $productCollectionFactory,
        ProductRepositoryInterface $productRepository,
        DateTime $date
    ) {
        $this->productCollectionFactory = $productCollectionFactory;
        $this->productRepository = $productRepository;
        $this->date = $date;
    }

    public function execute()
    {
        $currentDate = $this->date->date();
        $expiredProductsCollection = $this->productCollectionFactory->create();
        $expiredProductsCollection
            ->addFieldToFilter(
                'special_to_date',
                [
                    'notnull' => 1,
                    'lteq' => $currentDate
                ]
            )
            ->addFieldToFilter(
                'special_price',
                [
                    'notnull' => 1
                ]
            );

        /** @var \Magento\Catalog\Model\Product $product */
        foreach($expiredProductsCollection as $product) {
            try {
                $product = $this->productRepository->get($product->getSku(), true);
                $product->setSpecialToDate(null);
                $product->setSpecialPrice(null);
                $product->setSpecialFromDate(null);
                $this->productRepository->save($product);
            } catch (\Exception $e){}
        }
    }
}
  • Thanks for comment , but its not working – Chala Chalapathi Oct 18 '18 at 5:31
  • This is tested code, working fine for me. – Sohel Rana Oct 18 '18 at 5:45
  • Hi @SohelRana Where do you put this code? – ineluki Oct 30 '18 at 11:30
  • @ineluki this is cron example. So create cron related xml and added this code. – Sohel Rana Oct 30 '18 at 12:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.