1

I want to add custom clickable URL for the category image. Anyone can teach me what I need to do? I have to create a new attributes for the URL field?

enter image description here

1 Answer 1

0

below i have given the steps to follow and code implementation too:

  1. You need to install the category attribute
  2. You need to display that attribute in the admin side in the "Content" group and below the category image
  3. In the frontend , we need to modify the "category.image" block to add the anchor link tag to make the category images clickable

Code level implemenation:

  1. First you need to register a module and enable it as these are basics so have not given code.

  2. For installing the category attribute please place a file inside your module in this path = app/code/OX/PrintSampleContent/Setup/Patch/Data/InstallCategoryAttribute.php

  3. Next , your patch file should contains this code:

    <?php
    
    namespace OX\PrintSampleContent\Setup\Patch\Data;
    
    use Magento\Catalog\Model\Category;
    use Magento\Catalog\Setup\CategorySetup;
    use Magento\Catalog\Setup\CategorySetupFactory;
    use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;
    use Magento\Framework\Setup\ModuleDataSetupInterface;
    use Magento\Framework\Setup\Patch\DataPatchInterface;
    use Magento\Framework\Setup\Patch\PatchRevertableInterface;
    
    class InstallCategoryAttribute implements DataPatchInterface, PatchRevertableInterface
    {
    
    /**
     * @var ModuleDataSetupInterface
     */
    private $moduleDataSetup;
    
    /**
     * @var CategorySetupFactory
     */
    private $categorySetupFactory;
    
    /**
     * PatchInitial constructor.
     * @param ModuleDataSetupInterface $moduleDataSetup
     * @param CategorySetupFactory $categorySetupFactory
     */
    public function __construct(
        ModuleDataSetupInterface $moduleDataSetup,
        CategorySetupFactory $categorySetupFactory
    ) {
        $this->moduleDataSetup = $moduleDataSetup;
        $this->categorySetupFactory = $categorySetupFactory;
    }
    
    /**
     * {@inheritdoc}
     */
    public static function getDependencies()
    {
        return [];
    }
    
    /**
     * {@inheritdoc}
     */
    public static function getVersion()
    {
        return '1.0.0';
    }
    
    public function apply()
    {
        /** @var CategorySetup $categorySetup */
        $categorySetup = $this->categorySetupFactory->create(['setup' => $this->moduleDataSetup]);
        $categorySetup->addAttribute(Category::ENTITY, 'clickable_url', [
            'type' => 'varchar',
            'label' => 'Clickable URL For Image',
            'input' => 'text',
            'visible' => true,
            'required' => false,
            'global' => ScopedAttributeInterface::SCOPE_WEBSITE,
            'group' => 'Display Settings',
        ]);
    }
    
    public function revert()
    {
        /** @var CategorySetup $categorySetup */
        $categorySetup = $this->categorySetupFactory->create(['setup' => $this->moduleDataSetup]);
        $categorySetup->removeAttribute(Category::ENTITY, 'clickable_url');
    }
    
    /**
     * {@inheritdoc}
     */
    public function getAliases()
    {
        return [];
    }
    

    }

  4. After saving this file , you need to place another file to display this attribute in the admin side , please paste the code in this path = app/code/OX/PrintSampleContent/view/adminhtml/ui_component/category_form.xml

    <?xml version="1.0"?>
    <form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"      xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <fieldset name="content">
        <field name="clickable_url" sortOrder="50" formElement="input">
            <settings>
                <dataType>string</dataType>
                <label translate="true">Clickable URL For Image</label>
                <notice translate="true">Only relative URL is supported</notice>
            </settings>
        </field>
    </fieldset>
    
  5. After pasting these two files you can execute the command = bin/magento setup:upgrade via command line to install this attribute into your magento instance database.

  6. You can check the attribute in the admin side in the category edit mode page , if the field is not below the category image try changing the sort order as some magento instance may have many custom attribute same like this , please see the image below for ref: enter image description here

  7. Next we need to work on the frontend to make the category images clickable for that we need to over-ride this block = category.image , please paste this code into this path = app/code/OX/PrintSampleContent/view/frontend/layout/catalog_category_view.xml

    <?xml version="1.0"?>
    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="category.view.container">
                <referenceBlock name="category.image"
                       template="OX_PrintSampleContent::category/image.phtml"/>
        </referenceContainer>
    </body>
    
  8. After that we need to copy the template from this original path of module catalog Module_Catalog::category/image.phtml and use it in our module as we need to make changes to image tag , pleae paste this below into this path = app/code/OX/PrintSampleContent/view/frontend/templates/category/image.phtml

     <?php
     $_category  = $block->getCurrentCategory();
     $_imgHtml   = '';
     if ($_imgUrl = $block->getImage()->getUrl($_category)) {
     $_imgHtml = '<div class="category-image"><a href="'.$_category->getClickableUrl().'"><img src="'
        . $block->escapeUrl($_imgUrl)
        . '" alt="'
        . $block->escapeHtmlAttr($_category->getName())
        . '" title="'
        . $block->escapeHtmlAttr($_category->getName())
        . '" class="image"/></a></div>';
    $_imgHtml = $block->getOutput()->categoryAttribute($_category, $_imgHtml, 'image');
    /* @noEscape */ echo $_imgHtml;
       }
       ?>
    
  9. Please clean the cache to see the expected results

  10. Please note that these sample codes are only for sample purposes and not exact task requirement , please do comment and give a like if this post helped you as this helps me answer more answers.

Thanks.

1
  • thanks for the feedback, I will give it a try first and get back to you. Thank you!
    – Paul Fan
    Oct 11, 2022 at 3:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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