0

How to change all products titles using script or coding in Magento 2. I need to change all the products title on product description page.

1

etc\di.xml

<?xml version="1.0"?><config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Catalog\Model\Product" 
type="Magepow\Product\Plugin\Model\Catalog\Product" /></config>

Magepow\Product\Plugin\Model\Catalog\Product.php

namespace Magepow\Product\Plugin\Model\Catalog;
class Product extends \Magento\Catalog\Model\Product{
    public function getName(){
              return $this-_getData(self::NAME) . ' + Hello WO';
          }
    public function getSku(){
              return "Demo-Hello";
          }
}
0

If you want to change all products titles then you can use a preference or modify it you can use a preference like below : In your etc/di.xml add this:

    <preference for="Magento\Catalog\Model\Product" type="Vendor\Module\Model\Product" />

and in Vendor\Module\Model\Product.php, add below code :

<?php
namespace Vendor\Module\Model;

class Product extends \Magento\Catalog\Model\Product
{
    public function getName()
    {
         $changeNamebyPreference = $this->_getData('name') . ' MODIFIED BY PREFERENCE';
         return $changeNamebyPreference;
    }
}

$this->_getData('name') returns products default title.

0

Step 1: Create app/code///etc/di.xml

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Catalog\Model\Product">
        <plugin name="change_catalog_product_title" type="<vendorName>\<moduleName>\Plugin\Catalog\Model\Product"/>
    </type>
</config>

Step 2: app/code/<moduleName>/Plugin/Catalog/Model/Product.php

<?php

namespace <vendorName>\<moduleName>\Plugin\Catalog\Model;

class Product
{
    public function afterGetName(\Magento\Catalog\Model\Product $subject, $result)
    {
        // $title = $subject->getAttributeText(''); // call any custom attr like this of current product
        $title = "hello";
        return $title." - ". $result . ' MODIFIED BY PREFERENCE';
    }
}

That's it - Happy Coding

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.