1

I would like to add a custom block in category landing page, after the product price section,

Iam using the below code but it is adding after the add to cart but i wants to add after price section,

  <referenceContainer name="category.product.addto.compare">
    <block class="Magento\Framework\View\Element\Template" template="Vendor_Module::category/banner_category.phtml" name="banner_category_ptk" after="category.products.list"/>

Please help me how to do this, what is proper container name i have to use in magento2

1 Answer 1

5

I don't think using layout you will easily add this block after price section.I guess that you are trying to add this block to every product

and, using Plugin on the method getProductPrice() and add a block after Price section on listing section.

So. create Around plugin on the function getProductPrice() and your block output HTML to this function.

The di.xml file in your module declares a plugin for a class object:

<?xml version="1.0"?>
<config>
    <type name="Magento\Catalog\Block\Product\AbstractProduct">
      <plugin name="add_custom_block" type="My\Module\Plugin\AddCustomBlock" sortOrder="1" disabled="false" />
    </type>
</config>

Plugin Class:

<?php

namespace My\Module\Plugin;


class AddCustomBlock
{
    public function afterGetProductPrice(
        \Magento\Catalog\Block\Product\AbstractProduct $subject,
        $output,
        \Magento\Catalog\Model\Product $product
    )
    {
        $customBlockHtml = '';
        $name = 'banner_category_ptk_' . $product->getId();
        $customBlock = $subject->getLayout()->getBlock($name);
        if (!$subject->getLayout()->getBlock($name)) {
            $customBlock = $subject->getLayout()->createBlock(
                \Magento\Framework\View\Element\Template::class,
                $name,
                ['product' => $product]
            );
        }


        if ($customBlock) {
            $customBlock->setTemplate('Vendor_Module::category/banner_category.phtml');
            $customBlockHtml = $customBlock->toHtml();
        }

        return $output . $customBlockHtml;
    }
}
9
  • Hi @Amit Thanks for your answer, i would like to add a custom div using banner_category.phtml so that i will written all my functoinality in that phtml file only. Dec 4, 2018 at 10:10
  • That div should add after the price section. Dec 4, 2018 at 10:10
  • 1
    @shivashankarm try with this ======= return $customBlockHtml; Dec 4, 2018 at 10:31
  • works fine what i m expect Apr 22, 2019 at 11:53
  • 1
    The answer is updated. Now the issue has been resolved.
    – Amit Bera
    Apr 9, 2021 at 3:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.