0

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="StackExchange\Magento\Observer\Frontend\Catalog\CategoryLoadAfter" 
              name="stackexchange_magento_observer_frontend_catalog_category_load_after"
    />
</event>

observer

public function execute(
\Magento\Framework\Event\Observer $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 \Magento\Catalog\Model\Category) {
  //$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.

1 Answer 1

1

I suggest to use the similar logic like described in https://magento.stackexchange.com/a/357049/91782

You need to create plugin for \Magento\Catalog\Block\Category\View and modify metadata on afterSetLayout.

Don't forget to change $subject, $result and return type to \Magento\Catalog\Block\Category\View

// category object is
$category = $subject->getCurrentCategory();
if ($category) {
    // update metadata

    // in original logic also present following
    $pageMainTitle = $layout->getBlock('page.main.title');
    if ($pageMainTitle) {
        $pageMainTitle->setPageTitle($category->getName());
    }
}

Alternative way is use beforeSetLayout instead of afterSetLayout and try to update category data. Signature:

    public function beforeSetLayout(CategoryBlock $subject, LayoutInterface $layout): array
    {
        $category = $subject->getCurrentCategory();
        if ($category) {
            $metaDesc = "Place order for " .$category->getName() . " with us and get huge sales and discount!";
            $category->setMetaDescription($metaDesc);
            // ...
        }

        return [$layout];
    }

I suggest to use afterSetLayout and update data into page config instead of replace category data runtime.

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.