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

TOP 7 ECOMMERCE PLATFORMS TO CONSIDER IN 2023

The last few years have witnessed the rise of the eCommerce platform with tons of features and look that suit each business’s requirements for   eCommerce websites . An eCommerce platform makes it possible for businesses to reach customers in online channels, hence helping increase the market size of the businesses.  While traditional eCommerce software is costly, not scalable, difficult to work with, and time-consuming considering customization and integration with other systems, the eCommerce platform is a better solution for creating relevant, engaging, and personalized online experiences. Among hundreds of eCommerce websites, you have to pick one that can decide the future of your business. In this article, we’ll explore 7 of the best eCommerce platforms and also cover their features, pros, cons, and whom they’re recommended for most, so take a look below, you can have all the key details and see which is a perfect fit for your unique business needs. 7 Best eCommerce platf...

HONEST MAGENTO 2 REVIEW FOR ALL ECOMMERCE MERCHANTS

Ecommerce has had a significant impact on the way businesses do business. Nowadays, you can do the majority of your business tasks with a few clicks of the mouse or a few taps on your mobile device. While there are many big players in e-commerce or e-business, Magento 2 has been the front runner in the online business world – all due to the number of good things it offers. However, at some point, the average person is going to hit a wall. In today’s article, we’re going to focus on compiling a list of Magento 2 reviews so that you can learn everything about the platform from its background to key features, pros, and cons and decide whether you’d want Magneto for your e-commerce or not. What is Magento 2 platform? For online retailers, Magento is the most popular e-commerce platform. It is a high-performance, scalable solution with robust out-of-the-box capabilities and a big community of developers who are constantly adding new features to the platform. Magento 2 is the compan...

HOW TO JOIN TABLES PROGRAMMATICALLY IN MAGENTO 2

Today we talk about How to join tables programmatically in Magento 2. Sometimes you need to get join collection with product collection data or category collection data or order collection or custom table collection. In order to make you do that with ease, the developer team from Magenest recommends the topic join tables in Magento2. Here we go. How to join tables in SQL? A SQL Join statement is used to combine data or rows from two or more tables based on a common field between them. Different types of Joins are: INNER JOIN : Returns records that have matching values in both tables. LEFT JOIN : Returns all records from the left table, and the matched records from the right table. RIGHT JOIN : Returns all records from the right table, and the matched records from the left table. FULL JOIN : Returns all records from both tables. ( we don’t use this much) For this sample, we have the following tables: Director_id Name 1 Magenest director 2 Magenest 3 Son Tung 4 Cris 5 Magento2 Magenest_d...