Magento2 SEO – Automated Meta Descriptions

magento2meta-descriptionmeta-title

We currently have meta data set up in the individual products. However, I would create an automated meta description for all products (including backdating old products).

I know I could do this through import/export – but I want something that is automated going forward.

For example, my product meta description should be '[brand], [product-name], buy online today.'

I can find how to do this for opengraph meta content but not meta descriptions and key words.

Can anyone please assist?

Best Answer

In this case, you can use event/observer.

Fire an observer on the event catalog_product_load_after at frontend area set meta description on the fly.

Create events.xml at app/code/StackExchange/Magento/etc/frontend/ and as `events.xml location under on frontend and this event only fire for frontend area.

events.xml code

<?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_product_load_after">
        <observer instance="StackExchange\Magento\Observer\Frontend\Catalog\ProductLoadAfter" 
                  name="stackexchange_magento_observer_frontend_catalog_productloadafter_catalog_product_load_after"
        />
    </event>
</config>

Create Observer class ProductLoadAfter at app/code/StackExchange/Magento/Observer/Frontend/Catalog/.

ProductLoadAfter.php code

<?php

namespace StackExchange\Magento\Observer\Frontend\Catalog;

class ProductLoadAfter implements \Magento\Framework\Event\ObserverInterface {

    /**
     * @var \Psr\Log\LoggerInterface
     */
    private $logger;

    public function __construct(
     \Psr\Log\LoggerInterface $logger
    ) {

        $this->logger = $logger;
    }
    /**
     * Execute observer
     *
     * @param \Magento\Framework\Event\Observer $observer
     * @return void
     */
    public function execute(
        \Magento\Framework\Event\Observer $observer
    ) {
        $this->logger->debug(__METHOD__);
        $product = $observer->getEvent()->getProduct();
        if ($product instanceof \Magento\Catalog\Model\Product) {
            $newMetaDescription = $product->getData('brand') .$product->getData('name').'-'. __('buy online today');
            $product->setMetaDescription($newMetaDescription);
           // $product->setMetaKeyword('TEST '.$newMetaDescription);
        }
    }

}

Some notes:

Assume that brand is text type attribute. If the brand is an attribute of type drop attribute then you need to some extra code as $product->getData('brand') only give brand option id not it label mean brand name example, Puma, addidas.

Also, your module must have:

  1. app/code/{Vendor}/{Modulename}/etc/module.xml
  2. app/code/{Vendor}/{Modulename}/composer.json
  3. app/code/{Vendor}/{Modulename}/registration.php

After adding the event you should flush the cache.

Related Topic