Skip to main content

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.

>> Sourcehttps://magenest.com/en/configure-special-price-in-magento-2-programmatically/

Comments

Popular posts from this blog

WHAT IS A SHOPIFY DEVELOPMENT STORE AND WAYS TO CRAFT AN IMPRESSIVE DEMO STORE

  Are you seeking to fashion a polished and tailor-made online store using Shopify? Uncover the potential of a Shopify development store. Within this manual, we will delve into the essence of a Shopify development store and its role as a launchpad for constructing, personalizing, and assessing your Shopify store before its official launch. Let's explore and tap into the opportunities presented by this comprehensive guide to Shopify development stores. Understanding Shopify Development Stores A Shopify development store is a complimentary account accessible to Shopify Partners. This account empowers them to build and test themes, applications, or complete Shopify stores. As a Shopify Partner, your Partner Dashboard allows the creation of an unrestricted number of development stores. These stores serve multiple valuable purposes: - Testing: Utilize development stores to test themes, apps, or customizations without impacting your live store's operation. - Client Setup: Development...

4 ESSENTIAL PILLARS FOR PROPER DIGITAL TRANSFORMATION JOURNEY

  Every business is on a digital transformation journey, though they may not realize it. In its simplest form, digital transformation is the process of using technology to create new or improved business processes. However, undertaking a total digital transformation project for your business can be daunting, as it requires a complete rethinking of how a business operates. The good news is that there are plenty of resources available to help businesses make the transition. From consultants and software providers to online articles and webinars, there is no shortage of advice for companies embarking on a digital transformation journey. So what does a digital transformation journey actually mean? And how to start the digital transformation with it? Here are some essential steps to make sure your journey is a success. By following these guidelines, you’ll be able to improve your business and stay ahead of the curve in today’s constantly-changing technological landscape. Why Should You ...

HOW MUCH DOES MAGENTO 2 COST? WHAT IS THE INVESTMENT EXPENSE FOR A PROPER MAGENTO 2 SYSTEM

Magento 2 is still a popular eCommerce platform, and in this Magento pricing guide, we’ll go through how much does Magento 2 cost to establish and manage a Magento store. Among a number of eCommerce platforms, Magento will not disappoint you with a wide range of functionalities, enhanced security mechanisms, and, most importantly, completely free customisation. Many merchants, though, wonder, “How much does Magento cost?” This includes the fees of purchasing a license, hosting alternatives, and other necessities for running a successful Magento store. What is Magento 2? Magento 2 is an open-source e-commerce platform developed by Varien Inc’s Roy Rubin and Yoav Kutner. Magento was first made available on March 31, 2007. It is a handy software for online businesses and the world’s largest E-commerce platform. Because of its sophisticated, scalable architecture, Magento 2 is the most popular CMS (Content Management System) for creating online stores all over the world. It is compatible w...