Magento 2 Both Including & Excluding Tax Price Show Only On Product Detail Page

Magento 2 Both Including & Excluding Tax Price Show Only On Product Detail Page

Hello Magento Techies ?,

What’s going on guys? I am back with a new solution, Magento 2 Both Including & Excluding Tax Price Show Only On Product Detail Page. You can also catch up on our lastly published blog, How to Add Split Button on Admin Sales Order View Page in Magento 2.

Introduction:

Showing the tax prices in the product detail page has the benefit that the customer can see the total price of the product and is not caught off guard at the end of the purchase. At times, the store owner need not include tax price for selected products or according to the location on the product detail page. Magento does not provide any configuration to show including and excluding tax price on the product detail page, so here I will show how to do that technically. Let’s start out ?

Steps to Show Including & Excluding Tax Price Only On Product Detail Page:

Step 1: First you need to add di.xml in the following path:

app\code\Vendor\Extension\etc\di.xml

Now add the below code

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
   <type name="Magento\Catalog\Helper\Data">
      <plugin name="Vendor_Catalog_Helper_Data" type="Vendor\Extension\Plugin\Catalog\Helper\Data" sortOrder="10" disabled="false" />
   </type>
   <type name="Magento\Tax\Pricing\Render\Adjustment">
      <plugin name="Vendor_Tax_Pricing_Render_Adjustment" type="Vendor\Extension\Plugin\Tax\Pricing\Render\Adjustment" sortOrder="10" disabled="false" />
   </type>
   <type name="Magento\Framework\Pricing\Adjustment\Calculator">
      <plugin name="Vendor_Framework_Pricing_Adjustment_Calculator" type="Vendor\Extension\Plugin\Framework\Pricing\Adjustment\Calculator" sortOrder="10" disabled="false" />
   </type>
</config>

Step 2: Next, you need to add Data.php file in the following path:

app\code\Vendor\Extension\Plugin\Catalog\Helper\Data.php

And add the below code

<?php

namespace Vendor\Extension\Plugin\Catalog\Helper;
use Magento\Tax\Api\Data\TaxClassKeyInterface;
use Magento\Tax\Model\Config;

class Data extends \Magento\Catalog\Helper\Data
{
    public function aroundGetTaxPrice(\Magento\Catalog\Helper\Data $subject,
                                      callable $proceed,
                                      $product,
                                      $price,
                                      $includingTax = null,
                                      $shippingAddress = null,
                                      $billingAddress = null,
                                      $ctc = null,
                                      $store = null,
                                      $priceIncludesTax = null,
                                      $roundPrice = true)
     {
        if (!$price) 
        {
            return $price;
        }
        $store = $this->_storeManager->getStore($store);
        if (1) 
        {
            if ($priceIncludesTax === null) 
            {
                $priceIncludesTax = $this->_taxConfig->priceIncludesTax($store);
            }
            $shippingAddressDataObject = null;
            if ($shippingAddress === null) 
            {
                $shippingAddressDataObject =
                    $this->convertDefaultTaxAddress($this->_customerSession->getDefaultTaxShippingAddress());
            } 
            elseif ($shippingAddress instanceof \Magento\Customer\Model\Address\AbstractAddress) 
            {
                $shippingAddressDataObject = $shippingAddress->getDataModel();
            }
            $billingAddressDataObject = null;
            if ($billingAddress === null) 
            {
                $billingAddressDataObject =
                    $this->convertDefaultTaxAddress($this->_customerSession->getDefaultTaxBillingAddress());
            } 
            elseif ($billingAddress instanceof \Magento\Customer\Model\Address\AbstractAddress) 
            {
                $billingAddressDataObject = $billingAddress->getDataModel();
            }
            $taxClassKey = $this->_taxClassKeyFactory->create();
            $taxClassKey->setType(TaxClassKeyInterface::TYPE_ID)
                ->setValue($product->getTaxClassId());
            if ($ctc === null && $this->_customerSession->getCustomerGroupId() != null) 
            {
                $ctc = $this->customerGroupRepository->getById($this->_customerSession->getCustomerGroupId())
                    ->getTaxClassId();
            }
            $customerTaxClassKey = $this->_taxClassKeyFactory->create();
            $customerTaxClassKey->setType(TaxClassKeyInterface::TYPE_ID)
                ->setValue($ctc);
            $item = $this->_quoteDetailsItemFactory->create();
            $item->setQuantity(1)
                ->setCode($product->getSku())
                ->setShortDescription($product->getShortDescription())
                ->setTaxClassKey($taxClassKey)
                ->setIsTaxIncluded($priceIncludesTax)
                ->setType('product')
                ->setUnitPrice($price);
            $quoteDetails = $this->_quoteDetailsFactory->create();
            $quoteDetails->setShippingAddress($shippingAddressDataObject)
                ->setBillingAddress($billingAddressDataObject)
                ->setCustomerTaxClassKey($customerTaxClassKey)
                ->setItems([$item])
                ->setCustomerId($this->_customerSession->getCustomerId());
            $storeId = null;
            if ($store) 
            {
                $storeId = $store->getId();
            }
            $taxDetails = $this->_taxCalculationService->calculateTax($quoteDetails, $storeId, $roundPrice);
            $items = $taxDetails->getItems();
            $taxDetailsItem = array_shift($items);
            if ($includingTax !== null) 
            {
                if ($includingTax) 
                {
                    $price = $taxDetailsItem->getPriceInclTax();
                } 
                else 
                {
                    $price = $taxDetailsItem->getPrice();
                }
            } 
            else 
            {
                switch ($this->_taxConfig->getPriceDisplayType($store)) 
                {
                    case Config::DISPLAY_TYPE_EXCLUDING_TAX:
                    case Config::DISPLAY_TYPE_BOTH:
                        $price = $taxDetailsItem->getPrice();
                        break;
                    case Config::DISPLAY_TYPE_INCLUDING_TAX:
                        $price = $taxDetailsItem->getPriceInclTax();
                        break;
                    default:
                        break;
                }
            }
        }
        if ($roundPrice) 
        {
            return $this->priceCurrency->round($price);
        } 
        else 
        {
            return $price;
        };
    }
    private function convertDefaultTaxAddress(array $taxAddress = null)
    {
        if (empty($taxAddress)) 
        {
            return null;
        }
        $addressDataObject = $this->addressFactory->create()
            ->setCountryId($taxAddress['country_id'])
            ->setPostcode($taxAddress['postcode']);
        if (isset($taxAddress['region_id'])) 
        {
            $addressDataObject->setRegion($this->regionFactory->create()->setRegionId($taxAddress['region_id']));
        }
        return $addressDataObject;
    }
}

Step 3: Now you need to add Adjustment.php file in the following path:

app\code\Vendor\Extension\Plugin\Tax\Pricing\Render\Adjustment.php

Add the below code

<?php

namespace Vendor\Extension\Plugin\Tax\Pricing\Render;

class Adjustment
{
    protected $request;
    public function __construct(\Magento\Framework\App\Action\Context  $request)
    {
        $this->request = $request;
    }
    public function aroundDisplayBothPrices(\Magento\Tax\Pricing\Render\Adjustment $subject, callable $proceed)
    {
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $request = $this->request->getRequest();
        if ($request->getFullActionName() == 'catalog_product_view') 
        {
            return 1;
        }
        else
        {
            $result = $proceed();
        }
    }
}

Step 4: Lastly,  you need to add Calculator.php file in the following path:

app\code\Vendor\Extension\Plugin\Framework\Pricing\Adjustment\Calculator.php

And add the below code

<?php
namespace Vendor\Extension\Plugin\Framework\Pricing\Adjustment;

use Magento\Framework\Pricing\SaleableInterface;
class Calculator extends \Magento\Framework\Pricing\Adjustment\Calculator
{
    public function aroundGetAmount(\Magento\Framework\Pricing\Adjustment\Calculator $subject, callable $proceed,$amount, SaleableInterface $saleableItem, $exclude = null, $context = [])
    {
        $baseAmount = $fullAmount = $amount;
        $previousAdjustments = 0;
        $adjustments = [];
        foreach ($saleableItem->getPriceInfo()->getAdjustments() as $adjustment) 
        {
            $code = $adjustment->getAdjustmentCode();
            $toExclude = false;
            if (!is_array($exclude)) 
            {
                if ($exclude === true || ($exclude !== null && $code === $exclude)) 
                {
                    $toExclude = true;
                }
            } 
            else 
            {
                if (in_array($code, $exclude)) 
                {
                    $toExclude = true;
                }
            }
            if ($adjustment->isIncludedInBasePrice()) 
            {
                $adjust = $adjustment->extractAdjustment($baseAmount, $saleableItem, $context);
                $baseAmount -= $adjust;
                $fullAmount = $adjustment->applyAdjustment($fullAmount, $saleableItem, $context);
                $adjust = $fullAmount - $baseAmount - $previousAdjustments;
                if (!$toExclude) 
                {
                    $adjustments[$code] = $adjust;
                }
             } 
             elseif (1) 
             {
                if ($toExclude) 
                {
                    continue;
                }
                $newAmount = $adjustment->applyAdjustment($fullAmount, $saleableItem, $context);
                $adjust = $newAmount - $fullAmount;
                $adjustments[$code] = $adjust;
                $fullAmount = $newAmount;
                $previousAdjustments += $adjust;
            }
        }
        return $this->amountFactory->create($fullAmount, $adjustments);
        return $result;
    }
}

This is it.

Conclusion:

Hope, all are able to show including and excluding tax price on the product detail page. In case of any obstacle, mention in the comment section below. I will love to help you out. Do not forget to share with your friends and social media platforms. Enjoy the weekend and stay in touch with us for Magento solutions. 

Happy Programming ?

Previous Article

Magento Extensions Digest July 2020 (New Release & Updates)

Next Article

How to Change Default Language in Magento 2

Write a Comment
  1. How about this:
    “`
    public function aroundDisplayBothPrices(\Magento\Tax\Pricing\Render\Adjustment $subject, callable $proceed)
    {
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $request = $this->request->getRequest();
    if ($request->getFullActionName() == ‘catalog_product_view’)
    {
    return 1;
    }
    else
    {
    return $proceed();
    }
    }“`

    Where is the return value in the else statement?
    4 stars?

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨