Magento – add store name dynamically to all product meta titles

magento2productseo

Tried adding {{store}} and {{store_name}} in the Mask for Meta Title to output the site name on each product in the Product Fields Auto-Generation. Any idea if possible or what the correct store name variable is?
enter image description here

Best Answer

Unfortunately auto-generation fields doesn't allow to use store name for mask. And store name could be a problem to generate product meta title in this way because every product could be assigned to the website.

Furthermore I do not think you need this way to generate product title. Here is way would be more useful I think..

Create new module

app/code/Vendor/Module/registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Vendor_Module',
    __DIR__
);

app/code/Vendor/Module/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Vendor_Module" setup_version="2.1.0"/>
</config>

you need to define new event

app/code/Vendor/Module/etc/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_product_load_after">
        <observer name="vendor_product_load_after" instance="Vendor\Module\Observer\AfterProductLoad" />
    </event>
</config>

and add event handler app/code/Vendor/Module/Observer/AfterProductLoad.php

<?php
namespace Vendor\Module\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Event\Observer as EventObserver;
use Magento\Store\Model\StoreManagerInterface;

class AfterProductLoad implements ObserverInterface
{
    /**
     * @var StoreManagerInterface
     */
    private $storeManager;

    /**
     * @param StoreManagerInterface $storeManager
     */
    public function __construct(
        StoreManagerInterface $storeManager
    ){
        $this->storeManager = $storeManager;
    }

    public function execute(EventObserver $observer)
    {
        $product = $observer->getProduct();
        if ($product->getIsMetaApplied()) {
            return;
        }
        if ($metaTitle = $product->getMetaTitle()) {
            $metaTitle .= ' | ' . $this->storeManager->getStore()->getName();
            $product->setMetaTitle($metaTitle);
            $product->setIsMetaApplied(true);
        }
    }
}

do not forget to upgrade system

php bin/magento setup:upgrade

Hope this helps.

Related Topic