X

Установка url-keys для товаров на основе их названия в Magento

Код для установки url-keys для товаров на основе их названия в Magento..

<?php
die('Disabled in script code to prevent unwanted changes');
 
    require 'app/Mage.php';
    Mage::app();
 
    function generateUrlKey( $productName )
    {
        $read = Mage::getSingleton('core/resource')->getConnection('core_read');
        $urlKey = Mage::getModel('catalog/product_url')->formatUrlKey($productName);
        $sql = 'SELECT * FROM catalog_product_entity_varchar WHERE attribute_id = (SELECT attribute_id FROM eav_attribute WHERE attribute_code = "url_key" AND entity_type_id = 4) AND value = ? and store_id = 0';
        $row = $read->fetchRow($sql, array($urlKey));
        $idx = 0;
        while ($row != false) {
            $prefix = '';
            if ($idx) $prefix = '-' . $idx;
            $urlKey = Mage::getModel('catalog/product_url')->formatUrlKey($productName) . $prefix;
            $idx++;
            $row = $read->fetchRow($sql, array($urlKey));
        }
        return $urlKey;
    }
 
    set_time_limit(0);
?>
<html>
<head>
  <title>Url-key updater</title>
  <style type="text/css">
    body {font-family:Tahome; font-size:11px;}
  </style>
</head>
<body>
<?php
    $keysSet = 0;
    $keysExists = 0;
    $serial = 1;
    $model = Mage::getModel('catalog/product');
    $products = $model->getCollection();
    foreach ($products as $product)
    {
        if (!empty($_REQUEST['skip']) AND $serial<intval($_REQUEST['skip']))
        {
            $serial++;
            continue;
        }
 
        $model->load($product->getId());
        echo 'SKU '.$model->getSku().'] '.$model->getName().' = ';
 
        if (empty($_REQUEST['updateall']) AND $key = $model->getUrlKey() AND preg_match('~^[a-z0-9-]+$~', $key))
        {
            $keysExists++;
            echo 'key exists: <span style="color:green">'.htmlspecialchars($key).'</span>';;
        }
        else
        {
            $keysSet++;
            $key = generateUrlKey($model->getName());
            try{
                $product->setUrlKey($key)->save();
            }
            catch (Exception $e)
            {
                echo 'key save err: <span style="color:red">'.htmlspecialchars($key).'</span>';;
            }
            echo 'new key: <span style="color:blue">'.htmlspecialchars($key).'</span>';;
        }
 
        $websiteIds = $product->getWebsiteIds();
        if (is_array($websiteIds)) $websiteIds = implode(',',$websiteIds);
 
        echo '(serial:'.$serial.'; websiteIds:'.$websiteIds.')';
        $serial++;
        echo '<br />';
    }
?>
<hr />
Keys exists:<?php echo $keysExists; ?> |
Keys set:<?php echo $keysSet; ?>
</body>
</html>

 

Категории: Magento