Tax Price Show Only On Product Detail Page

Written by Jigar Patel

Oct 13, 2022

Tax Price Show Only On Product Detail Page

Magento does not provide any configuration to include and exclude tax prices on the product detail page, so I will show how to do that technically.

Magento 2 default displays the original product price as configured from the admin panel. It does not include the tax amount that a customer has to pay. The benefit of tax prices on the product detail page has the customer can see the tax price of the product and is not conceiving off guard at the end of the purchase.

How to Get all Options of a Custom Attribute in Magento 2

Excluding Tax: Prices that appear on the storefront do not include tax.
Including Tax: Prices that appear on the storefront include tax.

You can include & exclude tax prices shown only on the product detail page in Magento 2 with the below step.

We are already learned how to create a basic module in Magento 2. We need to create module.xml and registration.php files. You can create module.xml and registration.php  from this tutorial.

Here we are using Dolphin as Vendor name and Price as the name of the module.  You can change this according to your Vendor and Module name.

Step 1: Create Dependency injection

Create dependency injection file di.xml in the app/code/Dolphin/Price/etc folder with the following 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="Dolphin_Catalog_Helper_Data" type="Dolphin\Price\Plugin\Catalog\Helper\Data" sortOrder="10" disabled="false" />
    </type>
    <type name="Magento\Tax\Pricing\Render\Adjustment">
        <plugin name="Dolphin_Tax_Pricing_Render_Adjustment" type="Dolphin\Price\Plugin\Tax\Pricing\Render\Adjustment" sortOrder="10" disabled="false" />
    </type>
    <type name="Magento\Framework\Pricing\Adjustment\Calculator">
        <plugin name="Dolphin_Framework_Pricing_Adjustment_Calculator" type="Dolphin\Price\Plugin\Framework\Pricing\Adjustment\Calculator" sortOrder="10" disabled="false" />
    </type>
</config>

Step 2: Create plugin class Data.php

Create the plugin class file View.php in the app/code/Dolphin/Price/Plugin/Catalog/Helper folder with the following code.

<?php

namespace Dolphin\Price\Plugin\Catalog\Helper;

use Magento\Tax\Api\Data\TaxClassKeyInterface;

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: Create plugin class Calculator.php

Create the plugin class file Calculator.php in the app/code/Dolphin/Price/Plugin/Framework/Pricing/Adjustment folder with the following code.

<?php

namespace Dolphin\Price\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);
    }
}

Step 4: Create plugin class Adjustment.php

Create the plugin class file Adjustment.php in the app/code/Dolphin/Price/Plugin/Tax/Pricing/Render folder with the following code.

<?php0

namespace Dolphin\Price\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();
        }
    }
}

Result:- 

After you implement the above code, check the output on the product page. The tax prices will be displayed on the product page.

Tax Price Show Only On Product Detail Page

 

 

I Hope, This instruction will be helpful for you.

If you have any difficulties regarding this blog, do consider them posting in the Comments section below!

I’m here to help.

Thank you!

Jigar Patel

Author

We can help you with

  • Dedicated Team
  • Setup Extended Team
  • Product Development
  • Custom App Development

Schedule a Developer Interview And Get 7 Days Risk-Free Trial

Fill out This Form and one of Our Technical Experts will Contact you Within 12 Hours.

    Google
    |

    4.8

    Google
    |

    4.8

    Google
    |

    4.9

    Google
    |

    4.8

    Google
    |

    4.9

    Copyright © 2024 DOLPHIN WEB SOLUTION. All rights reserved.

    TO TOP