How to clean cache by tag id in Magento 2

Written by Chirag Parmar

May 31, 2022

How to clean cache by tag id in Magento 2

Magento 2 provide good cache mechanism for faster serving pages to browser. Sometimes we require to clean cache by tag id as per custom requirement. In recent projects there was custom requirement in which customer want to clear cache for particular cms page only after save it. So i did it in detail and found better solution for clear cache for cms page , catalog product , catalog category and even you can clear cache for custom module also.

How to Find / Identfy tag of frontend section for clean cache by tag id ?

In this article i will explain how you can identify tag for clear cache for particular area of magento site. Cache id is used to identify a specific cache record. If you save something in the cache you can later retrieve it by its id. First of all you need to find proper CACHE_ID and CACHE_TAG. You can find it easily by opening particular model.

For example if you open “vendor/magento/module-catalog/Model/Product.php” then you will see kind of below code :

How to clean cache by tag id in Magento 2
These tags are used for clear cache by tags.

So now let see how can we clean caches partially with tags,

private $fullPageCache;

private function getCache()
{
    if (!$this->fullPageCache) {
        $this->fullPageCache = \Magento\Framework\App\ObjectManager::getInstance()->get(
            \Magento\PageCache\Model\Cache\Type::class
        );
    }
    return $this->fullPageCache;
}

public function cleanByTags()
{
    $productId = 21; //Id of the Product whose Cache need to be cleaned 
    $tags = ['CAT_P_'.$productId];
    $this->getCache()->clean(\Zend_Cache::CLEANING_MODE_MATCHING_TAG, $tags);
}

Chirag Parmar

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