How do I add “Pay as little as $/month” on product view page based on the final price?
-
19-03-2021 - |
Question
I would like to display what the monthly payments would be for our monthly payment option, based on the final price of the product (including configurable products). Here is a screenshot of something I would like:
Essentially, I would like to be able to grab the final price and split it into monthly payments and output the text after the "product.info.price".
I tried overriding the catalog_product_view.xml
in my theme and specify a different .phtml to use, but I was not able to grab the final price... or any price for that matter.
I also tried specifying the block class="Magento\Catalog\Pricing\Render" in the catalog_product_view.xml
, but it just repeated the product price with a lot of underlying html with no way to modify it.
So, how can I override the catalog_product_view.xml
to grab the price, do a calculation based on it, then output custom text based on that calculation after the "product.info.price" block?
Solution
create catalog_product_view.xml
file under
app/design/frontend/Vendor/Theme/Magento_Catalog/layout/catalog_product_view.xml
and use the code below:
<referenceContainer name="product.info.main">
<block class="Magento\Catalog\Block\Product\View" name="monthly_payment_text" template="Magento_Catalog::product/view/monthly_payment.phtml" after="product.info.price" />
</referenceContainer>
create monthly_payment.phtml
file under
app/design/frontend/Vendor/Theme/Magento_Catalog/templates/product/view/monthly_payment.phtml
and use the code below:
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$priceHelper = $objectManager->create('Magento\Framework\Pricing\Helper\Data');
$product = $this->getProduct();
$finalPrice = $product->getFinalPrice();
$month = 12;
$monthlyPay = round(($finalPrice/$month), 2);
$monthlyPay = $priceHelper->currency($monthlyPay, true, false);
?>
<p>Pay as little as <?php echo $monthlyPay; ?>/mo for <?php echo $month; ?> Months</p>
Hope this will help you!