Magento2 – Generate URL Keys and Meta Data

backendmagento2product

A backend user created hundreds of products by cloning one product. Now URL keys and meta data are all wrong because they are based on the first product name. Is it possible to regenerate all url keys and meta data using the actual product name ?

Doing this by hand would take hours…

Best Answer

Your question has 2 questions: 1. how to regenerate the url keys in Magento 2. how to regenerate the meta data in Magento

To resolve 1: you need to first clear the url keys and then save the attributes and this needs to be done in a batch script

Subset of the code needed:

use Magento\CatalogUrlRewrite\Model\ProductUrlRewriteGenerator;

/** @var $item \Magento\Catalog\Model\Product $item **/
$item->setUrlKey('');
$item->setUrlKey($this->productUrlPathGenerator->getUrlKey($item));
$item->getResource()->saveAttribute($item, 'url_key');

after this is executed for all your skus, you need to generate url rewrite although the cron will do this for you

  1. to resolve 2, you could follow the same method resetting the attributes "meta_title, meta_keywords, meta_description". However, without being SEO specialist, your meta data should contain more than just the words in the product name. Ideally, you should have some meta data in a csv file that would just be something you can import. If you need just product name, then just set the values for these attribute to product name

I have a full code repository showing how to do the url keys and url rewrite at: https://bitbucket.org/magstaging/urlrewrite

Related Topic