1

I currently have the following script, that change the producttitle of a product with a specific ID.

Now I want to re-write the script, so that it does not update the attributes but generates a .csv file of the entire catalog with two columns.

  1. Product_SKU
  2. $productnamingseo value

How can I achieve this?

ini_set('display_errors', 'On');
error_reporting(E_ALL);

require('../app/Mage.php');
Mage::app();

$product = Mage::getModel('catalog/product')->load(409728);
Mage::register('current_product', $product);
$seotitle = Mage::helper('seo')->getCurrentSeo();
$productnamestring = Mage::getSingleton('seo/object_product')->getTitle();

        $findseo = array('/\h+inch (?:(i[357])-\w+|\h+\w+)?/', '/(\w+)#\w+/', '/(^| )(.{4,}) (.*)\2/', '/\s*-\s*$/');
        $replaceseo = array('" $1', '$1', '$1$2 $3', '');
        $productnamingseo = preg_replace($findseo, $replaceseo, $productnamestring);

$product->setName($productnamingseo);
$product->getResource()->saveAttribute($product, 'name');

EDIT already tried this, that works for only 1 product. All other products got that $productnamingseo value of product 1, instead of their own unique value.

This create a .csv file with the following output. Only the first line is correct. All other lines got the wrong $productnamingseo of the first product.

"ACER_EY.JE001.002","Acer C120 LED - EY.JE001.002"
"ALLIEDTELESIS_AT-2701FXA/SC-001","Acer C120 LED - EY.JE001.002"
"APC_0M-0213-005","Acer C120 LED - EY.JE001.002"

Script:

ini_set('display_errors', 'On');
error_reporting(E_ALL);
ini_set('memory_limit', '4G');

require('app/Mage.php');
Mage::app();

$file_path = "var/import/productname.csv";
$mage_csv = new Varien_File_Csv();

$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('*')->setPageSize(1)->setCurPage(1);

foreach ($products as $product) {
    $prod = Mage::register('current_product', $product);
    $seotitle = Mage::helper('seo')->getCurrentSeo();
    $productnamestring = Mage::getSingleton('seo/object_product')->getTitle();

    $findseo = array('/\h+inch (?:(i[357])-\w+|\h+\w+)?/', '/(\w+)#\w+/', '/(^| )(.{4,}) (.*)\2/', '/\s*-\s*$/');
    $replaceseo = array('" $1', '$1', '$1$2 $3', '');
    $productnamingseo = preg_replace($findseo, $replaceseo, $productnamestring);

    echo $productnamingseo;

    $data = array();
    $data['sku'] = $product->getSku();
    $data['name'] = $productnamingseo;
    $products_row[] = $data;

    Mage::unregister('current_product')
}

$mage_csv->saveData($file_path, $products_row);
echo 'Done!';

SEO helper Mirasvit_Seo_Model_Object_Product:

public function _construct()
{
    parent::_construct();
    $this->_product = Mage::registry('current_product');
    if (!$this->_product) {
        $this->_product = Mage::registry('product');
    }
    if (!$this->_product) {
        return;
    }


    $this->_parseObjects['product'] = $this->_product;

    $this->setAdditionalVariable('product', 'url', $this->_product->getProductUrl());
    $this->setAdditionalVariable('product', 'final_price', $this->_product->getFinalPrice());
    $this->setAdditionalVariable('product', 'final_price_minimal', Mage::helper('seo')->getCurrentProductFinalPrice($this->_product));
    $this->setAdditionalVariable('product', 'final_price_range', Mage::helper('seo')->getCurrentProductFinalPriceRange($this->_product));
    $this->setAdditionalVariable('product', 'stock_qty', Mage::helper('seo')->getCurrentProductStockQty($this->_product));


    $categoryId = $this->_product->getSeoCategory();
    $this->_category = Mage::registry('current_category');

    if ($this->_category && !$categoryId) {
        $this->_parseObjects['category'] = $this->_category;
    } elseif ($this->_product) {
        if (!$categoryId) {
            $categoryIds = $this->_product->getCategoryIds();
            if (count($categoryIds) > 0) {
                //we need this for multi websites configuration
                $categoryRootId = Mage::app()->getStore()->getRootCategoryId();
                $category = Mage::getModel('catalog/category')->getCollection()
                            ->addFieldToFilter('path', array('like' => "%/{$categoryRootId}/%"));

                //don't delete (for some stores need main_table)
                $stringSelect = $category->getSelect()->__toString();
                $entityIdFilter = (strpos($stringSelect, 'main_table') !== false)
                    ? 'main_table.entity_id' : 'entity_id';

                $category = $category->addFieldToFilter($entityIdFilter, $categoryIds)
                            ->setOrder('level', 'desc')
                            ->setOrder($entityIdFilter, 'desc')
                            ->getFirstItem()
                        ;
                $categoryId = $category->getId();
            }
        }
        //load category with flat data attributes
        $category = Mage::getModel('catalog/category')->load($categoryId);
        $this->_category = $category;
        $this->_parseObjects['category'] = $category;
        if (!Mage::registry('seo_current_category')) {// to be sure that register will not be done twice
            Mage::register('seo_current_category', $category);
        };
    }

    $this->_parseObjects['store'] = Mage::getModel('seo/object_store');

    $this->init();
}

getCurrentSeo() code:

public function getCurrentSeo()
{
    if (Mage::app()->getStore()->getCode() == 'admin') {
        return new Varien_Object();
    }

    $isCategory = Mage::registry('current_category') || Mage::registry('category');
    $isProduct  = Mage::registry('current_product') || Mage::registry('product');
    $isFilter   = false;

    if ($isCategory) {
        $filters = Mage::getSingleton('catalog/layer')->getState()->getFilters();
        $isFilter = count($filters) > 0;
    }

    if ($isProduct) {
        $seo = Mage::getSingleton('seo/object_product');
    } elseif ($isCategory && $isFilter) {
        $seo =  Mage::getSingleton('seo/object_filter');
    } elseif ($isCategory) {
        $seo =  Mage::getSingleton('seo/object_category');
    } else {
        $seo = new Varien_Object();
    }

    if ($seoTempalate = $this->checkTempalateRule($isProduct, $isCategory, $isFilter)) {
        foreach ($seoTempalate->getData() as $k=>$v) {
            if ($v) {
               $seo->setData($k, $v);
            }
        }
    }

    if ($seoRewrite = $this->checkRewrite()) {
        foreach ($seoRewrite->getData() as $k=>$v) {
            if ($v) {
               $seo->setData($k, $v);
            }
        }
    }

    $storeId = Mage::app()->getStore()->getStoreId();
    $page    = Mage::app()->getFrontController()->getRequest()->getParam('p');
    if (!$page) {
        $page = 1;
    }

    if ($isCategory && !$isProduct) {
        if ($this->_titlePage) {
            switch ($this->_config->getMetaTitlePageNumber($storeId)) {
                case Mirasvit_Seo_Model_Config::META_TITLE_PAGE_NUMBER_BEGIN:
                    if ($page > 1) {
                        $seo->setMetaTitle(Mage::helper('seo')->__("Page %s | %s", $page, $seo->getMetaTitle()));
                        $this->_titlePage = false;
                    }
                    break;
                case Mirasvit_Seo_Model_Config::META_TITLE_PAGE_NUMBER_END:
                    if ($page > 1) {
                        $seo->setMetaTitle(Mage::helper('seo')->__("%s | Page %s", $seo->getMetaTitle(), $page));
                        $this->_titlePage = false;
                    }
                    break;
                case Mirasvit_Seo_Model_Config::META_TITLE_PAGE_NUMBER_BEGIN_FIRST_PAGE:
                    $seo->setMetaTitle(Mage::helper('seo')->__("Page %s | %s", $page, $seo->getMetaTitle()));
                    $this->_titlePage = false;
                    break;
                case Mirasvit_Seo_Model_Config::META_TITLE_PAGE_NUMBER_END_FIRST_PAGE:
                    $seo->setMetaTitle(Mage::helper('seo')->__("%s | Page %s", $seo->getMetaTitle(), $page));
                    $this->_titlePage = false;
                    break;
            }
        }

        if ($this->_descriptionPage) {
            switch ($this->_config->getMetaDescriptionPageNumber($storeId)) {
                case Mirasvit_Seo_Model_Config::META_DESCRIPTION_PAGE_NUMBER_BEGIN:
                    if ($page > 1) {
                        $seo->setMetaDescription(Mage::helper('seo')->__("Page %s | %s", $page, $seo->getMetaDescription()));
                        $this->_descriptionPage = false;
                    }
                    break;
                case Mirasvit_Seo_Model_Config::META_DESCRIPTION_PAGE_NUMBER_END:
                    if ($page > 1) {
                        $seo->setMetaDescription(Mage::helper('seo')->__("%s | Page %s", $seo->getMetaDescription(), $page));
                        $this->_descriptionPage = false;
                    }
                    break;
                case Mirasvit_Seo_Model_Config::META_DESCRIPTION_PAGE_NUMBER_BEGIN_FIRST_PAGE:
                    $seo->setMetaDescription(Mage::helper('seo')->__("Page %s | %s", $page, $seo->getMetaDescription()));
                    $this->_descriptionPage = false;
                    break;
                case Mirasvit_Seo_Model_Config::META_DESCRIPTION_PAGE_NUMBER_END_FIRST_PAGE:
                    $seo->setMetaDescription(Mage::helper('seo')->__("%s | Page %s", $seo->getMetaDescription(), $page));
                    $this->_descriptionPage = false;
                    break;
            }
        }

        if ($page > 1) {
            $seo->setDescription(''); //set an empty description for page with number > 1 (to not have a duplicate content)
        }
    }

    if ($metaTitleMaxLength = $this->_config->getMetaTitleMaxLength($storeId)) {
        $metaTitleMaxLength = (int)$metaTitleMaxLength;
        if ($metaTitleMaxLength < Mirasvit_Seo_Model_Config::META_TITLE_INCORRECT_LENGTH) {
            $metaTitleMaxLength = Mirasvit_Seo_Model_Config::META_TITLE_MAX_LENGTH; //recommended length
        }
        $seo->setMetaTitle($this->_getTruncatedString($seo->getMetaTitle(), $metaTitleMaxLength, $page));
    }

    if ($metaDescriptionMaxLength = $this->_config->getMetaDescriptionMaxLength($storeId)) {
        $metaDescriptionMaxLength = (int)$metaDescriptionMaxLength;
        if ($metaDescriptionMaxLength < Mirasvit_Seo_Model_Config::META_DESCRIPTION_INCORRECT_LENGTH) {
            $metaDescriptionMaxLength = Mirasvit_Seo_Model_Config::META_DESCRIPTION_MAX_LENGTH; //recommended length
        }
        $seo->setMetaDescription($this->_getTruncatedString($seo->getMetaDescription(), $metaDescriptionMaxLength, $page));
    }

    return $seo;
}
  • I think this is a general PHP question on how to write a CSV files, which has been answered numerous times, for example here: stackoverflow.com/questions/35364528/… – simonthesorcerer Dec 13 '18 at 13:25
  • @simonthesorcerer Not really, because I also need a solution to change it from 1 product to all products. See my edit. – Henk Z Dec 13 '18 at 14:13
  • So the code from the edit only saves one product instead of all products? The first or the last one? – simonthesorcerer Dec 13 '18 at 14:33
  • @simonthesorcerer No the edit is the last part, to update all products and create a csv. – Henk Z Dec 13 '18 at 14:35
  • Yes, what happens when you execute that? Do you get an error, a message, does anything happen? – simonthesorcerer Dec 13 '18 at 14:39
3

I get a PHP Fatal error: Allowed memory size of 2147483648 bytes exhausted. I guess due to some wrong code

This is not from errors in the code, but from "waste of resources". It basically means that your script is executed without errors, but the RAM that PHP is allowed to use for this process (2G in this case) is not enough, and PHP breaks while executing.

Fast & easy solution: assign more RAM!

<?php
ini_set('memory_limit', '4G');
// rest of code [...]

But this will only help a bit. The server might become very slow while you export, or maybe you have so many SKUs and attributes that this still won't help.

It's better to use objects that are smaller, load less data etc. For example replace this:

$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('*');

...with this:

$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect(['sku', 'name', 'the_name_of_your_seo_attribute']);

...to load only the attributes you really need.

If you have a lot of products, it may also be helpful to export them in chunks of, say, 10k products:

$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect(['sku', 'name', 'the_name_of_your_seo_attribute'])
->setPageSize(10000)->setCurPage(1);

(increase setCurPage() for each new set)

Hope that helps!

  • Thanks! It now does create a csv file, but only the contains now the SKU. So my previous code to load the value of $productnamingseo does not work. Mage::register('current_product', $product); is a important part of the previous script. What am I missing here? – Henk Z Dec 13 '18 at 15:53
  • I also tried $products = Mage::getModel('catalog/product')->getCollection()->setPageSize(10000)->setCurPage(1); but that still only loads the SKU. – Henk Z Dec 13 '18 at 15:53
  • Mage::register('current_product', $product); does not load the product, it only registers it globally. You have to adjust the addAttributeToSelect() part. Looking into the functionality of the SEO-helper should help - you will see which attributes are required there. – simonthesorcerer Dec 13 '18 at 15:58
  • It loads many attributes and is different for each product. So we need to set it to $products = Mage::getModel('catalog/product')->getCollection()->setPageSize(10000)->setCurPage(1); So that it load all attributes. But then still the csv only contains the SKU. – Henk Z Dec 13 '18 at 16:06
  • This code does not load all attributes, it only loads the attributes that are configured as "visible in the product listing" in the Magento backend. You had addAttributeToSelect('*'), this loads all attributes. And it's too much for your server. – simonthesorcerer Dec 13 '18 at 16:13
1

Mirasvit uses singleton pattern everywhere and the registered product, because it assumes it is getting the data from the frontend when the product is selected. The singleton pattern is somewhat unnecessary and I feel a bad design decision on their part. However, due to using Singleton pattern, A script like this won't work as it doesn't destruct the product object, thus you get same seo information for every product

Hence, the need to rewrite all the functions used with Model pattern instead of Singleton Pattern.

I rebuilt all the Mirasvit SEO functions replacing the Singleton patterns with a Model pattern. Since it dynamically replaces the information, it is done all in the script and not through the Mirasvit classes.

<?php

ini_set('display_errors', 'On');
error_reporting(E_ALL);
ini_set('memory_limit', '4G');

require('app/Mage.php');
Mage::app();

$file_path = "var/import/productname.csv";
$mage_csv = new Varien_File_Csv();
$products_row = $_parseObjects = $_additional = [];
$_product = null;
$_storeId = Mage::app()->getStore()->getId();
$_config = Mage::getModel('seo/config');

$products = Mage::getModel('catalog/product')
    ->getCollection()
    ->addAttributeToSelect('*');

foreach ($products as $product) {
    global $_product;
    $_product = $product;
    $seo = getCurrentSeo();

    $productnamestring = $seo->getTitle();

    echo 'Seo Title: ' . $productnamestring . "\n";

    $findseo = array('/\h+inch (?:(i[357])-\w+|\h+\w+)?/', '/(\w+)#\w+/', '/(^| )(.{4,}) (.*)\2/', '/\s*-\s*$/');
    $replaceseo = array('" $1', '$1', '$1$2 $3', '');
    $productnamingseo = preg_replace($findseo, $replaceseo, $productnamestring);

    $data = array();
    $data['sku'] = $product->getSku();
    $data['name'] = $productnamingseo;
    $products_row[] = $data;
}

$mage_csv->saveData($file_path, $products_row);
echo 'Done!';

function getCurrentSeo()
{
    global $_product;
    global $_storeId;
    global $_config;

    if ($_product) {
        $seo = Mage::getModel('seo/object_product');
    } else {
        $seo = new Varien_Object();
    }

    if ($seoTempalate = checkTempalateRule()) {
        foreach ($seoTempalate->getData() as $k=>$v) {
            if ($v) {
                $seo->setData($k, $v);
            }
        }
    }

    if ($seoRewrite = checkRewrite($_product)) {
        foreach ($seoRewrite->getData() as $k=>$v) {
            if ($v) {
                $seo->setData($k, $v);
            }
        }
    }

    $page = 1;

    if ($metaTitleMaxLength = $_config->getMetaTitleMaxLength($_storeId)) {
        $metaTitleMaxLength = (int)$metaTitleMaxLength;
        if ($metaTitleMaxLength < Mirasvit_Seo_Model_Config::META_TITLE_INCORRECT_LENGTH) {
            $metaTitleMaxLength = Mirasvit_Seo_Model_Config::META_TITLE_MAX_LENGTH; //recommended length
        }
        $seo->setMetaTitle(_getTruncatedString($seo->getMetaTitle(), $metaTitleMaxLength, $page));
    }

    if ($metaDescriptionMaxLength = $_config->getMetaDescriptionMaxLength($_storeId)) {
        $metaDescriptionMaxLength = (int)$metaDescriptionMaxLength;
        if ($metaDescriptionMaxLength < Mirasvit_Seo_Model_Config::META_DESCRIPTION_INCORRECT_LENGTH) {
            $metaDescriptionMaxLength = Mirasvit_Seo_Model_Config::META_DESCRIPTION_MAX_LENGTH; //recommended length
        }
        $seo->setMetaDescription(_getTruncatedString($seo->getMetaDescription(), $metaDescriptionMaxLength, $page));
    }

    return $seo;
}

function checkTempalateRule($info = false)
{
    global $_product;

    if (isset($_product)) {
        $collectionProduct = Mage::getModel('seo/template')->getCollection()
            ->addStoreFilter(Mage::app()->getStore())
            ->addFieldToFilter('rule_type', Mirasvit_Seo_Model_Config::PRODUCTS_RULE)
            ->addActiveFilter()
            ->addSortOrder();

        $seoTemplateRule = _getTempalateRule($collectionProduct,
            $_product->getId(),
            false,
            $info);
    }

    return $seoTemplateRule;
}

function _getTempalateRule($collection, $productId, $categoryId, $info)
{
    global $_additional;
    global $_storeId;
    global $_parseObjects;

    $sortOrderAppliedId = false;
    $stopRulesProcessingAppliedId = false;

    foreach ($collection as $item) {
        if ($isElementApplied = _getElementApplied($productId, $item)) {
            $seoTemplateRule[$item->getId()] = $item;
            if ($item->getStopRulesProcessing() && !$stopRulesProcessingAppliedId) {
                $stopRulesProcessingAppliedId = $item->getId();
            }
            if ($item->getSortOrder() && !$stopRulesProcessingAppliedId) {
                $sortOrderAppliedId = $item->getId();
            }
        }
    }

    if ($info) {
        if ($stopRulesProcessingAppliedId) {
            $seoTemplateRule['applied'] = $stopRulesProcessingAppliedId; // stop rules processing
            $seoTemplateRule['stop_rules_processing'] = true;
        } elseif ($sortOrderAppliedId) {
            $seoTemplateRule['applied'] = $sortOrderAppliedId; // sort order
            $seoTemplateRule['sort_order'] = true;
        } elseif ($seoTemplateRule) {
            $seoTemplateRule['applied'] = key(array_slice($seoTemplateRule, -1, 1, true)); // maximal ID
        }

        return $seoTemplateRule;
    }

    if ($stopRulesProcessingAppliedId) {
        $seoTemplateRule = $seoTemplateRule[$stopRulesProcessingAppliedId]; // stop rules processing
    } elseif ($sortOrderAppliedId) {
        $seoTemplateRule = $seoTemplateRule[$sortOrderAppliedId]; // sort order
    } else {
        $seoTemplateRule = array_pop($seoTemplateRule); // maximal ID
    }

    if ($seoTemplateRule) {
        $_parseObjects = _addParseObjects();
        $seoTemplateRule->setTitle(Mage::helper('seo/parse')->parse($seoTemplateRule->getTitle(), $_parseObjects, $_additional, $_storeId));
        $seoTemplateRule->setDescription(Mage::helper('seo/parse')->parse($seoTemplateRule->getDescription(), $_parseObjects, $_additional, $_storeId));
        $seoTemplateRule->setShortDescription(Mage::helper('seo/parse')->parse($seoTemplateRule->getShortDescription(), $_parseObjects, $_additional, $_storeId));
        $seoTemplateRule->setFullDescription(Mage::helper('seo/parse')->parse($seoTemplateRule->getFullDescription(), $_parseObjects, $_additional, $_storeId));
        $seoTemplateRule->setCategoryDescription(Mage::helper('seo/parse')->parse($seoTemplateRule->getCategoryDescription(), $_parseObjects, $_additional, $_storeId));
        prepareMetaData($seoTemplateRule);
    }

    return $seoTemplateRule;
}

function _getElementApplied($productId, $item) {
        $isElementApplied = Mage::getModel('seo/template')->getRule($item->getTemplateId())->isProductApplied($productId);

    return $isElementApplied;
}

function checkRewrite($info = false)
{
    global $_additional;
    global $_storeId;
    global $_parseObjects;

    $uri = getBaseUri();
    $collection = Mage::getModel('seo/rewrite')->getCollection()
        ->addStoreFilter(Mage::app()->getStore())
        ->addEnableFilter()
        ->setOrder('sort_order');
    $resultRewrite = false;
    foreach ($collection as $rewrite) {
        if (checkPattern($uri, $rewrite->getUrl())) {
            $resultRewrite = $rewrite;
            break;
        }
    }

    if ($info && $resultRewrite) {
        return $resultRewrite;
    } elseif ($info) {
        return false;
    }

    if ($resultRewrite) {
        echo "hotes\n";
        $_parseObjects = _addParseObjects();
        $resultRewrite->setTitle(Mage::helper('parse')->parse($resultRewrite->getTitle(), $_parseObjects, $_additional, $_storeId));
        $resultRewrite->setDescription(Mage::helper('seo/parse')->parse($resultRewrite->getDescription(), $_parseObjects, $_additional, $_storeId));
        $resultRewrite->setMetaTitle(Mage::helper('seo/parse')->parse($resultRewrite->getMetaTitle(), $_parseObjects, $_additional, $_storeId));
        $resultRewrite->setMetaKeywords(Mage::helper('seo/parse')->parse($resultRewrite->getMetaKeywords(), $_parseObjects, $_additional, $_storeId));
        $resultRewrite->setMetaDescription(Mage::helper('seo/parse')->parse($resultRewrite->getMetaDescription(), $_parseObjects, $_additional, $_storeId));
    }

    return $resultRewrite;
}

function _addParseObjects() {
    global $_parseObjects;
    global $_product;

    if ($_product) {
        $_parseObjects['product'] = $_product;
        setAdditionalVariable('product', 'final_price', $_product->getFinalPrice());
        setAdditionalVariable('product', 'url', $_product->getProductUrl());
        setAdditionalVariable('product', 'final_price_minimal', Mage::helper('seo')->getCurrentProductFinalPrice($_product));
        setAdditionalVariable('product', 'final_price_range', Mage::helper('seo')->getCurrentProductFinalPriceRange($_product));
        setAdditionalVariable('product', 'stock_qty', Mage::helper('seo')->getCurrentProductStockQty($_product));
    }

    $_parseObjects['store'] = Mage::getModel('seo/object_store');
    $_parseObjects['pager'] = Mage::getModel('seo/object_pager');
    $_parseObjects['filter'] = Mage::getModel('seo/object_wrapper_filter');



    return $_parseObjects;
}

function getBaseUri()
{
    $baseStoreUri = parse_url(Mage::getUrl(), PHP_URL_PATH);

    if ($baseStoreUri  == '/') {
        return $_SERVER['REQUEST_URI'];
    } else {
        $requestUri = $_SERVER['REQUEST_URI'];
        $prepareUri = str_replace($baseStoreUri, '', $requestUri);
        if (substr($requestUri, 0, 1) == '/') {
            return $prepareUri;
        } else {
            return DS . $prepareUri;
        }
    }
}

function _getTruncatedString($str, $length, $page) {
    $usePageNumber       = false;
    $delimiterSymbols    = array(';', '',' ', ',', '.', '!', '?', "\n", "\r", "\r\n", '|');
    $delimiterEndSymbols = array(';', '',' ', ',', "\n", "\r", "\r\n", '|');

    if (strpos($str, ' | Page '.$page) !== false) {
        $str = str_replace(' | Page '.$page, '', $str);
        $length -= strlen(' | Page '.$page);
        $usePageNumber = true;
    }

    $truncatedString = Mage::helper('core/string')->substr($str, 0, $length);

    if(($finalStringPart = str_replace($truncatedString, '', $str))
        && !in_array(substr($finalStringPart, 0, 1), $delimiterSymbols)) {
        $truncatedStringArray = explode(" ", $truncatedString);
        if (count($truncatedStringArray) > 1) {
            array_pop($truncatedStringArray);
        }
        $truncatedString = implode(" ", $truncatedStringArray);
        if (in_array(substr($truncatedString, -1), $delimiterEndSymbols)) {
            $truncatedString = substr($truncatedString, 0, -1);
        }
    }

    if ($usePageNumber) {
        $truncatedString .= ' | Page '.$page;
    }

    return $truncatedString;
}

function setAdditionalVariable($objectName, $variableName, $value)
{
    global $_additional;
    global $_parseObjects;

    $_additional[$objectName][$variableName] = $value;
    if (isset($_parseObjects['product'])) {
        if ($objectName.'_'.$variableName == 'product_final_price_minimal') {
            $_parseObjects['product']->setData('final_price_minimal', $value);
        }
        if ($objectName.'_'.$variableName == 'product_final_price_range') {
            $_parseObjects['product']->setData('final_price_range', $value);
        }
        if ($objectName.'_'.$variableName == 'product_stock_qty') {
            $_parseObjects['product']->setData('stock_qty', $value);
        }
    }
}

function prepareMetaData($seoTemplateRule) {
    global $_additional;
    global $_product;
    global $_storeId;
    global $_parseObjects;
    global $_config;

    $metaTitle = $seoTemplateRule->getMetaTitle();
    $metaKeywords = $seoTemplateRule->getMetaKeywords();
    $metaDescription = $seoTemplateRule->getMetaDescription();

    if ($_config->isProductMetaTagsUsed() && $_product) {
        $metaTitle = trim($_product->getMetaTitle()) ? $_product->getMetaTitle() : $seoTemplateRule->getMetaTitle();
        $metaKeywords = trim($_product->getMetaKeyword()) ? $_product->getMetaKeyword() : $seoTemplateRule->getMetaKeywords();
        $metaDescription = trim($_product->getMetaDescription()) ? $_product->getMetaDescription() : $seoTemplateRule->getMetaDescription();

    }

    $seoTemplateRule->setMetaTitle(Mage::helper('seo/parse')->parse($metaTitle, $_parseObjects, $_additional, $_storeId));
    $seoTemplateRule->setMetaKeywords(Mage::helper('seo/parse')->parse($metaKeywords, $_parseObjects, $_additional, $_storeId));
    $seoTemplateRule->setMetaDescription(Mage::helper('seo/parse')->parse($metaDescription, $_parseObjects, $_additional, $_storeId));

}
  • Many thanks for your help. But with your code I currently get the original title of a product, instead of the dynamic SEO title. – Henk Z Dec 23 '18 at 14:34
  • hmm, ok let me look further. I don't have seo setup so I didn't check that – djfordz Dec 23 '18 at 14:58
  • @Henk Z did you try the latest answer / script? – djfordz Dec 24 '18 at 4:32
  • Thanks! I tried the latest one just now, but fetching the error: Fatal error: Uncaught Error: Using $this when not in object context in /test-product.php:540 – Henk Z Dec 24 '18 at 7:27
  • @Henk Z oops I added that very last, just remove return $this; at line 540 and will work. I removed it in answer. – djfordz Dec 24 '18 at 12:41

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.