- Get link
- X
- Other Apps
Methods to check if the product has a special price in Magento 2:
Methods to check if the product has a special price in Magento 2:
With Object Manager
12345678910111213141516171819<?php$product_id = 10; //Product ID$objectManager = \Magento\Framework\App\ObjectManager::getInstance();$_product = $objectManager->create('Magento\Catalog\Model\Product')->load($product_id);$orgprice = $_product->getPrice();$specialprice = $_product->getSpecialPrice();$specialfromdate = $_product->getSpecialFromDate();$specialtodate = $_product->getSpecialToDate();$today = time();if (!$specialprice)$specialprice = $orgprice;if ($specialprice< $orgprice) {if ((is_null($specialfromdate) &&is_null($specialtodate)) || ($today >= strtotime($specialfromdate) &&is_null($specialtodate)) || ($today <= strtotime($specialtodate) &&is_null($specialfromdate)) || ($today >= strtotime($specialfromdate) && $today <= strtotime($specialtodate))) {echo 'product has a special price';}}?>Block Method
12345678910111213141516171819202122232425262728use Magento\Catalog\Model\ProductFactory;protected $productFactory;public function __construct(ProductFactory $productFactory) {$this->productFactory = $productFactory;}public function getIsSpecialPrice($productId){$_product = $this->productFactory->create()->load($productId);$orgprice = $_product->getPrice();$specialprice = $_product->getSpecialPrice();$specialfromdate = $_product->getSpecialFromDate();$specialtodate = $_product->getSpecialToDate();$today = time();if (!$specialprice)$specialprice = $orgprice;if ($specialprice< $orgprice) {if ((is_null($specialfromdate) &&is_null($specialtodate)) || ($today >= strtotime($specialfromdate) &&is_null($specialtodate)) || ($today <= strtotime($specialtodate) &&is_null($specialfromdate)) || ($today >= strtotime($specialfromdate) && $today <= strtotime($specialtodate))) {return 1;}}return 0;}
That’s it!
- Get link
- X
- Other Apps
Comments
Post a Comment