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...

Enhance Your Shopify Store with Magenest's Expertise

  When it comes to developing a Shopify website, count on Magenest as your reliable partner. Whether you're new to Shopify, transitioning from another platform, or looking for ongoing support to improve your current site, we've got you covered. Magenest has a proven track record of success, ensuring your Shopify store achieves its maximum potential. Why Opt for Shopify? Shopify stands out as a user-friendly eCommerce platform assisting over 100,000,000 merchants worldwide in establishing their online stores. Offering a complete ecosystem for selling across websites, social media, and even offline, Shopify is an ideal solution for businesses of varying sizes and industries. As a cloud-based solution requiring no installations or hosting services, and with its cost-effectiveness, Shopify is an invaluable eCommerce platform that saves time and resources due to its exceptional usability. User-Friendly : Shopify provides a seamless starting point, even for individuals lacking techni...

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 ...