1

I am trying to set a meta description dynamically for Magento 2 categories as default rules. And I did manage to do it, here is my code.

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 am trying to find a way to add a check so that observer check first if this page has meta description set in backend categories, then it should skip adding meta description, but add if there is no meta description tag on the page.

  • You can use if condition if($category->getMetaDescription() == ''){ $category->setMetaDescription($metaDesc); } – Jaimin Sutariya Feb 27 at 8:34
  • post it as answer man, so i accept it, it helped solve problem quickly :) – Mr.Devops Feb 27 at 8:50
1

You can check if the category already has meta description and if not, set it with your custom text.

if($category->getMetaDescription() == '') { 
    $category->setMetaDescription($metaDesc);
}
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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