Question

I have created the category and added my custom code in that, I have also my custom block which I created for that I have used catalog_category_view.xml file but it affects in all other my category pages I want changes for this specific category can anyone tell me how can I do that?

Was it helpful?

Solution

Create a custom module then create the below files.

[Vendor]/[Module]/view/frontend/layout/catalog_category_view.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Vendor\Module\Block\SpecificCategory" name="specificcategory" template="Vendor_Module::custom_category.phtml" />
        </referenceContainer> 
    </body>
</page>

Block file

[vendor][Module]\Block\SpecificCategory.php

<?php 
namespace Vendor\Module\Block;

use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
use Magento\Framework\View\Page\Config;
use Magento\Framework\Registry;

class SpecificCategory extends Template
{
    private $_registry;

    public function __construct(
        Context $context,
        Config $pageConfig,
        Registry $registry,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->pageConfig = $pageConfig;
        $this->_registry = $registry;
    }

    public function getCurrentCategory() {
        $category_load = $this->_registry->registry('current_category');
        $currentId = $category_load->getId();
        if ($currentId) {
            //write code here for current_category and pass to the template.
        }

        return $currentId;
    }
}
?>

Template file to show output on the category page

[Vendor]/[Module]/view/frontend/templates/custom_category.phtml

<p><?= $block->getCurrentCategory(); ?></p>

Note:- You can impliment logic in block for specific category. I just add logic every current category.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top