How to configure Special Price in Magento 2 programmatically?

Introduction

Magento 2 special price is essentially a time-framed promotion, in which customers will enjoy a lower price than the base price of the product. It is displayed on both catalog listings and product pages. The regular price is shown as well, for the customer to see the difference.

From Magento 2 settings, you can get the special price configuration in the Advanced Settings of the individual product. In that, you only need to enter the number for the discounted price and the active time to apply.

In this blog, we show you  “How to configure Special Price in Magento 2 programmatically?”

Configure Special Price in Magento 2 programmatically

Sample code

<?php

namespace YourVendor\YourModule\Model;

use Exception;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Api\SpecialPriceInterface;
use Magento\Catalog\Api\Data\SpecialPriceInterfaceFactory;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;

class UpdateSpecialPrice
{
    /**
     * @var SpecialPriceInterface
     */
    private $specialPrice;

    /**
     * @var SpecialPriceInterfaceFactory
     */
    private $specialPriceFactory;
    /**
     * @var TimezoneInterface
     */
    protected $timezone;

    /**
     * UpdateSpecialPrice constructor.
     * @param SpecialPriceInterface $specialPrice
     * @param SpecialPriceInterfaceFactory $specialPriceFactory
     * @param TimezoneInterface $timezone
     */
    public function __construct(
        SpecialPriceInterface $specialPrice,
        SpecialPriceInterfaceFactory $specialPriceFactory,
        TimezoneInterface $timezone
    )
    {
        $this->specialPrice = $specialPrice;
        $this->specialPriceFactory = $specialPriceFactory;
        $this->timezone = $timezone;
    }

    /**
     * @param Product $product
     * @return bool
     * @throws Exception
     */
    public function getSpecialPriceData(Product $product)
    {
        $sku = $product->getSku();
        $storeId = $product->getStoreId();
        $yourSpecialPrice = 10.99; //(float) Special price value
        try {
            $dateFrom = '2021-07-01'; // future date to current date
            $dateTo = '2021-07-25'; // future date to price from

            $specialPriceFrom = $this->timezone->date($dateFrom)->format(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT); //(string) Special price from date value in Y-m-d H:i:s format in UTC
            $specialPriceTo = $this->timezone->date($dateTo)->format(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT); //(string) Special price to date value in Y-m-d H:i:s format in UTC.

            $prices = $this->specialPriceFactory->create();
            $prices->setSku($sku)
                   ->setStoreId($storeId)
                   ->setPrice($yourSpecialPrice)
                   ->setPriceFrom($specialPriceFrom)
                   ->setPriceTo($specialPriceTo);

            $specialProduct = $this->specialPrice->update($prices);
        } catch (Exception $exception) {
            throw new Exception($exception->getMessage());
        }
        return $specialProduct;
    }
}

Now, let’s understand the purpose of codes implemented:

  • We use the function update($price) that was implemented in Magento\Catalog\Api\SpecialPriceInterface to add/update special prices for products with SKU.
  • $sku = $product->getSku(): get  SKU of product that you want to set special price
  • $storeId = $product->getStoreId(): get store Id 
  • $specialPriceFrom = $this->timezone->date($dateFrom _>format(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT) : Format dateFrom value in Y-m-d H:i:s format in UTC
  • $specialPriceTo = $this->timezone->date($dateTo) _>format(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT): Format datTo  value in Y-m-d H:i:s format in UTC
  • $this->specialPriceFactory->create(): creates the object of SpecialPriceInterface and set SKU, storeId, special price, date from and date to for special price

Result

How-to-configure-Tier-Price-in-Magento-2-programmatically
Configure Special Price in Magento 2 programmatically

Conclusions

Whenever, we develop any custom module related to Payment, Shipping, Order Related, etc. at that time. If a special price is specified in a product, we must regard the special price as the price of that product instead of the original price. With the examples below, we have covered the basics of configuring special prices in Magento 2 programmatically. If you have any questions, feel free to leave your comments below.

Don't want to miss out on our latest insights?
Subscribe to our newsletter.

Disclaimer: By clicking submit, you agree to share your information with us to receive news, announcements, and resources when they are available.