Skip to content

How to set meta title dynamically for specific category in magento 2

I want to set meta title dynamically for specific category only and i getting meta title information based on url id(?id=1).
events.xml

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="catalog_category_load_after">
    <observer instance="StackExchangeMagentoObserverFrontendCatalogCategoryLoadAfter" 
              name="stackexchange_magento_observer_frontend_catalog_category_load_after"
    />
</event>

observer

public function execute(
MagentoFrameworkEventObserver $observer
) {
  $category = $observer->getEvent()->getCategory();
  $metaTitle = $category->getName() ." - xxx.club";
  $metaDesc = "Place order for " .$category->getName() . " with us and get huge sales and discount!";
  if ($category instanceof MagentoCatalogModelCategory) {
  //$oldMetaTitle = $category->getMetaTitle();
  $oldMetaDesc = $category->getMetaDesc();
  //$category->setMetaTitle($metaTitle);
  $category->setMetaDescription($metaDesc);
 }
}

I followed above solution. But its applying for all the categories in website.

Any help can be appreciated.
thanks.